I've seen a few versions of this question on here, but none of them seem to be the same as my issue, so figured I'd create a new question. I must be doing something very silly here, but for the life of me I cannot spot it.
I'll start with the context, although it is not particularly relevant: I am deferring loading of jQuery with js code, which means none of my code files can contain a $(document).ready(...) call, because "$" will be undefined at first pass. Instead I am adding my ready functions to a "global" array, and after jQuery loads asynchronously, I call all these functions with the following:
function FireLoadEvents() {
while ( OnLoadEvents.length > 0 ) {
var item = OnLoadEvents.splice(0,1);
item[0].ready();
}
}
Now in any of my page components I can use the following to add an event I wish to fire when jQuery is loaded and the document is actually ready:
OnLoadEvents.push( { ready: function() { ... } } );
I've defined the OnLoadEvents variable at the very top of my template in the head:
<script language="text/javascript">
var OnLoadEvents = new Array();
</script>
As you can see it is outside of any function scope, and it is also declared before it is referenced. When tested on its own, this setup is working great, but for some reason when it is added to my actual page heads, script tags later in the page are not able to add items to the OnLoadEvents variable. For instance the following is pulled into my template by a php-include server side, and adds these lines to the body of my page:
<script type='text/javascript'>
OnLoadEvents.push( { ready: function() {
if ( $('.sponsor-link').length != 0 ) {
...
}
} } );
</script>
When I hit this page in Chrome, it reports the following exception on the "push" line above:
Uncaught ReferenceError: OnLoadEvents is not defined
Any idea what is going on? Why would OnLoadEvents be undefined just a few lines down from where I initialize it? I'll note that I've also tried defining and referencing OnLoadEvents as window.OnLoadEvents.
Thanks in advance!
.ready(). Are you using theasyncordeferattribute? Are you using a script loader to load jQuery?var OnLoadEvents = [];instead ofvar OnLoadEvents = new Array();see: yuiblog.com/blog/2006/11/13/javascript-we-hardly-new-ya