Search

7/25/2008

Ajaxian » Getting around the blocking of script

Ajaxian » Getting around the blocking of script
Non-blocking JavaScript Downloads » Yahoo! User Interface Blog

Let's first take a look at what the problem is with the script downloads. The thing is that before fully downloading and parsing a script, the browser can’t tell what’s in it. It may contain document.write() calls which modify the DOM tree or it may even contain location.href and send the user to a whole new page. If that happens, any components downloaded from the previous page may never be needed.
If you do need several files though, you can attach a listener to the script’s onload event (this will work in Firefox) and the onreadystatechange event (this will work in IE).

demo
<head>
<script>
var url = 'http://www.w3clubs.com/comp.php?type=js&sleep=1';
for (var i = 0; i < 1; i++) {
var js = document.createElement('script');
js.src = url + '&id='+ i + new Date().getTime();
var head = document.getElementsByTagName('head')[0];
head.appendChild(js);
}
</script>
</head>

Dependencies

A problem with including scripts dynamically would be satisfying the dependencies. Imagine you’re downloading 3 scripts and three.js requires a function from one.js. How do you make sure this works?

Well, the simplest thing is to have only one file, this way not only avoiding the problem, but also improving performance by minimizing the number of HTTP requests (performance rule #1).

If you do need several files though, you can attach a listener to the script’s onload event (this will work in Firefox) and the onreadystatechange event (this will work in IE). Here’s a blog post that shows you how to do this. To be fully cross-browser compliant, you can do something else instead: just include a variable at the bottom of every script, as to signal “I’m ready”. This variable may very well be an array with elements for every script already included.

tag: performance

沒有留言: