Let's face it, jQuery/jQuery-ui is a heavy download.
Google recommends deferred loading of JavaScript to speed up initial rendering. My page uses jQuery to set up some tabs which are placed low on the page (mostly out of initial view) and I'd like to defer jQuery until AFTER the page has rendered.
Google's deferral code adds a tag to the DOM after the page loads by hooking into the body onLoad event:
<script type="text/javascript">
// Add a script element as a child of the body
function downloadJSAtOnload() {
var element = document.createElement("script");
element.src = "deferredfunctions.js";
document.body.appendChild(element);
}
// Check for browser support of event handling capability
if (window.addEventListener)
window.addEventListener("load", downloadJSAtOnload, false);
else if (window.attachEvent)
window.attachEvent("onload", downloadJSAtOnload);
else window.onload = downloadJSAtOnload;
</script>
I'd like to defer loading of jQuery this way, but when I tried it my jQuery code failed to find jQuery (not completely unexpected on my part):
$(document).ready(function() {
$("#tabs").tabs();
});
So, it seems I need to find a way to defer execution of my jQuery code until jQuery is loaded. How do I detect that the added tag has finished loading and parsing?
As a corollary, it appears that asynchronous loading may also contain an answer.
Any thoughts?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…