0
  function downloadJSAtOnload() {
 var element = document.createElement("script");
 element.src = "//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js";
 document.body.appendChild(element);
 }

 if (window.addEventListener)
 window.addEventListener("load", downloadJSAtOnload, false);
 else if (window.attachEvent)
 window.attachEvent("onload", downloadJSAtOnload);
 else window.onload = downloadJSAtOnload;

Ok so I'm using googles tip to defer loading of jQuery and fix any Render-blocking issue.

The issue happens when you are blocking external script during parsing which is loading jQuery or any other large javascript files that is not needed to render the above-the-fold region. So with the code above the issue is fixed. BUT I have one problem I have codes that run $(document).ready() but it bugs up because jQuery hasn't loaded yet.

How do I find out if jQuery has finished loading?

3
  • Are you able to inline the jQuery load within the HTML itself? Commented Jan 13, 2014 at 19:14
  • Well, if your other functions are reliant on $(document).ready(), just put the jQuery load in the head of your HTML, rather than injecting it with a script. Commented Jan 13, 2014 at 19:22
  • we need to defer jQuery because it will cause render-blocking so No we should not just load it on the head tag like we used to. Commented Jan 13, 2014 at 19:27

1 Answer 1

1

One option would be to put the script tag at the end of the body, or:

(function() {
  function getScript(url,success){
    var script=document.createElement('script');
    script.src=url;
    var head=document.getElementsByTagName('head')[0],
        done=false;
    script.onload=script.onreadystatechange = function(){
      if ( !done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete') ) {
        done=true;
        success();
        script.onload = script.onreadystatechange = null;
        head.removeChild(script);
      }
    };
    head.appendChild(script);
  }
    getScript('http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js',function(){
        // YOUR CODE GOES HERE AND IS EXECUTED AFTER JQUERY LOADS
    });
})();

From this answer: https://stackoverflow.com/a/5853358/1766140

Sign up to request clarification or add additional context in comments.

3 Comments

looks great. gonna try it out +1
I used @tylermwashburn answer from the link you gave. It was shorter and better IMHO. Thanks for the link very useful!
Agree, that one is cleaner.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.