Call (877) SITE-OPT (748-3678)

JavaScript: Delay Loading

Summary: Delay loading your JavaScripts to speed up your content display. By redefining empty stub functions with scripts loaded late in your page, you can ensure that your content displays quickly.

You can make your content display faster if you delay or defer the loading of your external JavaScript files. JavaScripts are executed as they are loaded. Any external JavaScripts referenced within the head of your XHTML documents must be executed before any body content is displayed. One way around this is to delay the loading of your external JavaScript by using empty "stub" functions, and redefining these functions later on.

Here's an example:

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

The empty stub function(s) allow users to interact with your page without generated "undefined" JavaScript errors. The scripts loaded just before the closing body tag redefine the stub function once the body content has displayed.

Be careful with this approach, however. Large JavaScript files, especially those that execute slowly, can bog down the response time of your page after it has loaded. Slow post-load response is more harmful to user satisfaction than slow page load times, according to current HCI research.

XSSI to Merge External JavaScripts

Even better, use XSSI to merge your script directly into your page, to avoid an extra HTTP request, like this:

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

Note that any functions defined in these delayed files will not be available until the page has loaded. For validation and overlaid menus, this shouldn't be a problem. Note also, that any scripts referenced outside of the head of your XHTML documents cannot be reliably compressed by modern browsers. We'll cover HTTP compression in a future tweak.

Further Reading

JavaScript: Defer Execution with the Defer Attribute
You can defer the execution of your JavaScripts with the defer attribute to speed initial content display. At least with IE4+ you can.
Optimizing JavaScript for Download Speed
Chapter 9 of Speed Up Your Site shows this and other time-saving techniques to speed up your scripts and reduce their footprint.

By website optimization on 26 Nov 2003 AM

Copyright © 2002-2013 Website Optimization, LLC. All Rights Reserved - Free website speed test - Privacy Policy
Last modified: August 26, 2013.

Follow us on: Twitter, Google+, Facebook, Linked In