Benny Tjia
Benny Tjia

Reputation: 4883

jQuery on the bottom, wait execution script on <head> until it is loaded

I saw similar question here in SO, where someone wants to do the same thing. The different case is that I have this lightweight script that listens for event bubbling to the top of the document root that I intentionally want to put on the top of the page and I dont want to wrap it inside $(document).ready(). It looks something like this:

<html>
<head>
    <script>
        document.documentElement.onclick = function (e) {
        //$.ajax call using jQuery. Possible that jQuery is not loaded when page is not completely loaded
        }
    </script>
</head>

And then near the bottom of the page I include jQuery like this:

<body>
    <script src="./jQuery.js"></script>
</body>
</html>

As you can see on the <head> when I'm making an ajax call to somewhere using $.ajax, it's possible that jQuery is not yet loaded, so that it may throw $ is undefined error when someone clicks on something on DOM, and jQuery is not loaded yet. My workaround is probably to use settimeout hoping that jquery will be loaded sometime later and the code is working like this:

if (typeof $ === 'undefined'){
  setTimeout(doAJAXJquery, 50);
}else{
  $.ajax(//blablabla) //jQuery loaded and ready to use!!
}

But it's a really dirty hack. How am I supposed to know when jQuery is finished loading? that 50ms i put there is only an arbitrary value i made up myself. Of course it is still not gonna work if jquery hasn;t been loaded yet and it already passes 50ms.

Is there any better workaround so when jQuery is undefined, it is gonna retry sometime later again, or put a function that executes ajax inside some callback that gets executed when jQuery is ready? thanks.

Upvotes: 1

Views: 526

Answers (2)

Cheery
Cheery

Reputation: 16214

If you want to execute the list of functions (or events 'fired') waiting for jQuery to load you could create your own 'ready' function :))

var runList = new Array(), timer = setInterval(function(){
  if (typeof(jQuery) != 'undefined')
  {
     clearInterval(timer);
     if (runList.length>0)  for(var i in runList) runList[i]();  
  }
}, 50);

runList.push(function(){alert(1);});
runList.push(function(){alert(2);});

var jQuery = 1;

Upvotes: 1

James Lin
James Lin

Reputation: 26558

what about

<head>
<script type="text/javascript">
var init = function(){
    document.documentElement.onclick = function (e) {
    //$.ajax call using jQuery. Possible that jQuery is not loaded when page is not completely loaded
    }
}
</script>
</head>
<body>
<script src="./jQuery.js"></script>
<script type="text/javascript">
init();
</script>
</body>

Upvotes: 1

Related Questions