How to lazy-load jQuery itself, especially when using $ (document) .ready ()
I am using jQuery in my website, for example:
<head>
<script src="http://ajax.googleapis.com/.../jquery.min.js" ...></script>
</head>
Then I use:
$(document).ready(function(){
});
In some cases, this event is used:
$(document).ready(function(){
var s = document.createElement("script");
s.type = "text/javascript";
s.async = true;
s.src = "http://www.script-host.com/.../script.js";
document.getElementsByTagName("head")[0].appendChild(s);
});
Now jquery.js seems to be (one of) the heaviest resource on my website in terms of file size. So I want to be lazy to load jquery.js, but I understand that this will cause all document.ready events to fail. What's the best workaround for this?
Maybe this recent article can help you: http://samsaffron.com/archive/2012/02/17/stop-paying-your-jquery-tax
the idea is to create a temporary $
function where you collect the entire function to be executed on the event domready
and then it is replaced later when you load jQuery at the bottom of the page.
You can load jQuery at the bottom of the page, not in <head>
. It will still use bandwidth, but it should be visually faster.