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: 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. Even better, use XSSI to merge your script directly into your page, to avoid an extra HTTP request, like this: 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.<script ...>
<!--
function stub(){};
// -->
</script>
</head>
<body>
...
<script src="/scripts/stub.js" type="text/javascript"></script>
</body>
XSSI to Merge External JavaScripts
<script type="text/javascript">
<!--#include virtual="/scripts/stub.js" -->
</script>
</body>
Further Reading
By website optimization on 26 Nov 2003 AM