Reputation: 572
i have the following code in the part of my html and was wondering how i could clean it up to optimize the loading.
<script type="text/javascript">
function downloadJSAtOnload() {
var element = document.createElement("script");
element.src = "js/jquery.orbit-1.2.3.min.js";
document.body.appendChild(element);
}
function downloadJSAtOnload() {
var element = document.createElement("script");
element.src = "http://code.jquery.com/jquery-latest.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;
</script>
Upvotes: 0
Views: 1025
Reputation: 1075597
If your goal is to allow the page to be displayed before the scripts are loaded, there's a much easier way: Just put the script tags (in the appropriate order) at the very end of the body
, just before the closing </body>
tag:
<!-- ...content of page... -->
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="js/jquery.orbit-1.2.3.min.js"></script>
</body>
</html>
The load
event on the window
object happens very late in the page load process, after all other resources have been completely loaded (or failed to load). So all images, both foreground and background, etc.
By putting the scripts right at the end of the body, you get them in the browser's download queue at a reasonable time, but without making the browser wait for the script to arrive before doing the initial page rendering. You also get the ordering (you'd get that with the defer
attribute on the script
element as well, but not all browsers support it). More: YUI Best Practices for Speeding Up your Website
You've asked in the comments when you would use the load
event for script loading. My answer is: I've never had a reason for doing so.
Upvotes: 2