Minimize HTTP Requests
Defer or Delay Loading
First introduced by Microsoft Internet Explorer 4, the defer attribute of the script element is now part of the HTML 4 and XHTML specifications. If your script does not produce any output, such as a function or array definition, you can use the defer attribute to give browsers a hint that they can defer execution until the rest of your HTML page loads. Here's an example:
Try to design or rewrite your scripts to encapsulate code in functions that will execute onload. Then you can defer their execution and still include them in the head of your document. This technique has the added benefit of allowing external files to be compressed, because they are included within the head. You can execute defined functions onload, like this:
Be careful with this approach because larger or multiple external scripts can bog down the response of your page after it displays. As you learned in Chapter 1, "Response Time: Eight Seconds, Plus or Minus Two," you want to avoid slow response times after a page loads. This technique works for HTML, but for XHTML you'll need to eliminate the surrounding SGML comments through conditional logic for post-HTML-3.2 browsers.
Even better, for high-traffic pages, SSI or merge them into the page to save an HTTP request. Here's an example of merging a script at the end of a page:
Functions called earlier in the page will not be available until the external file loads. You can include empty functions in the head, or better yet, check to be sure that external files have loaded or a flag has been defined to avoid calling nonexistent functions.
Place Compressed .js Files in the head
dom = (document.getElementById) ? true : false; ns4 = (document.layers) ? true : false; ie = (document.all) ? true : false; ie4 = ie && !dom; var src = ''; if (dom) src = '/dom.js'; else if (ie4) src = '/ie4.js'; else if (ns4) src = '/ns4.js'; document.write("<scr" + "ipt src=" + src + "><\/scr" + "ipt>");
This simple browser sniffer classifies browsers into four categories:
document.getElementById (~ DOM)
document.layers (Netscape 4)
document.all (Internet Explorer 4+)
You'll learn more advanced compatibility techniques that can save HTTP requests in Chapter 17, "Server-Side Techniques."