Home » JavaScript: Delay Loading

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.

5 thoughts on “JavaScript: Delay Loading”

  1. I am wandering i cant set a delay on a newWindow?
    setTimeout(window.open(“survey.asp”),10000); // opens a new window in 10sec
    but it opens it as soon as i click
    thanks

    Reply
  2. Moises: I know you posted that EVER SO LONG AGO, but I want to help out.
    try the following:
    setTimeout(‘window.open(“survey.asp”),10000);
    That should work out.

    Reply

Leave a Comment