Tuesday, March 17, 2009

Javascript/css/image loading

In Q&A-Javascript Execution & Onload Techniques in Web Browsers, It states that "Inline and external scripts are executed in the order in which they appear in an (x)HTML document…It should be noted that the loading of an (x)HTML page is halted while loading external JavaScript files."

In 14 Rules for Faster-Loading Web Sites, Rule 6 “Put script at the bottom” is used to avoid such halting. See Example.

Other resources (css/images) are loaded asynchronously and you cannot be certain when they will complete.

onload vs onDomReady
The onload event fires when the document and it's script/style/image resources are loaded, but you probably don't want to wait for images if you are doing any javascript when the page is loaded. Also, it may cause UI errors if the user tries to interact with the page before the JavaScript event handlers have been applied to the DOM via the onload event - a limitation of onload event. Instead, use something like jQuery's "ready" event or fire your own "DOMReady" event by placing a script tag at the end of the body:


<body>
<!-- your page contents here -->
<script type="text/javascript">
// DOM is ready, do scripty stuff now
DOMReady();
</script>
</body>

Single threaded script processing
The client-side javascript is single threaded. This means that the parsing of (x)HTML documents stops while scripts are loaded and executed, and that web browsers stop responding to user input while event handlers are being executed.

This is a good thing, and a bad thing. It's good because you can rest comfortable knowing that two event handlers will never run at the same time. Also, you can manipulate document content knowing that no other thread is attempting to modify the same piece of content.

It's bad in that intensive scripts can hold up the user experience by causing periods of unresponsiveness from a JavaScript driven UI.

No comments: