Reputation: 8292
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?
Upvotes: 0
Views: 539
Reputation: 3754
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
Upvotes: 1