Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > PHP/MySQL/Scripting

  • Print
  • + Share This
This chapter is from the book

Minimize HTTP Requests

Like CSS, your JavaScripts should be designed to maximize speed by minimizing the number of HTTP requests they require. You can embed smaller JavaScripts within high-traffic pages to avoid an extra HTTP request (with caveats for XHTML, discussed in Chapter 5, "Extreme XHTML"), and for site-wide bandwidth savings, use external files. Group files where possible to minimize the overhead of additional file requests.

Upon first encounter, external scripts take one HTTP request per file. I've found CSS files are cached more reliably than JavaScript files, however. External JavaScripts can continue to spawn HTTP requests even after their first encounter.5 Unlike HTML objects (like images, Flash, and Java), which can be requested in parallel, the HTML parser must wait for the JavaScript interpreter to load and execute any JavaScript files before it can continue.

Defer or Delay Loading

Scripts are executed as they are loaded. You can have multiple non-overlapping script elements within an HTML document, both in the head and body. To maximize page-display speed, try to defer or delay loading your JavaScripts where possible. Every byte and HTTP request you put before your viewable content delays its display.

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:

<script src="/later.js" defer="defer" type="text/javascript"></script>
</head>

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:

<body onload="later();">

Or you can avoid JavaScript errors in non-critical scripts that are triggered immediately (such as email validation or overlaid menus) by defining empty "stub" functions to be replaced by scripts that are redefined later:

<script>
<!--
function stub{};
// -->
</script>
</head>
<body>
...
<script src="/scripts/stub.js" type="text/javascript"></script> 
</body>

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:

<script type="text/javascript">
<!--#include virtual="newsticker.js" -->
</script>
</body>

We use this approach on WebReference.com's front page news flipper. We first embed a couple HTML news headlines within the flipper table, and then overlay these links with other stories with the delayed DHTML include. The main content displays first, and then the script loads—not vice versa. This technique gracefully degrades for folks without JavaScript. For more details, see http://www.webreference.com/headlines/nh/.

Delay Gotchas

There are some downsides to delaying external loading of JavaScript files. Moving larger or multiple external scripts to the end of the body just postpones the pain. Although your content may display faster, leaving your page can become slow and sticky.

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.

Finally, compressed JavaScripts located outside the head are not reliably decompressed by modern browsers. Instead, move compressed scripts inside the head and use the defer attribute where possible.

Place Compressed .js Files in the head

Because of the way the original Sun JavaScript parser worked, decompression of compressed external JavaScript files works only when they are embedded in the head of (X)HTML documents. We'll unravel that mystery in Chapter 18, "Compressing the Web."

Conditionally Load External JavaScripts

You can conditionally load external JavaScripts into your (X)HTML files with languages like JavaScript, XSSI, and PHP. Rather than create one large monolithic file, some authors split their JavaScript code into separate files. A common technique is to use separate libraries for Internet Explorer 4+, Netscape 4+, and DOM-based browsers (ie4.js, ns4.js, and dom.js, respectively). Depending on what type of browser loads the page, the following JavaScript loads only the necessary code:

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+)

  • Everything else

You'll learn more advanced compatibility techniques that can save HTTP requests in Chapter 17, "Server-Side Techniques."

  • + Share This
  • 🔖 Save To Your Account