Just another very quick blog post, this time about loading JavaScript files in web pages, and just a few quick tips, and gotcha’s about it.
This is by no means a definitive list, but if you can do most of these things, then you’re certainly on the right track!
Do not put ‘document.write’ into JS, the browser will have to to stop while it works out where to put this in the DOM, and how to render it. It will slow down your page.
To make things worse, if you put the JS at the bottom of the page, and put document.write in, you make it even slow, by making it the last thing the browser does.
Load JS files from a CDN or a different domain. However, the general limit is 4 domains in total (XHTML, CSS, JS, IMAGES etc). However, most people find that 2 is the best amount for the trade off between DNS lookups and extra concurrency.
Make JavaScript external – allowing the browser to cache full requests, rather than including it in the XHTML, and increasing the page request size
Related to the previous point, but make the external domains contain no cookies
Minify the JS
Put JS files at the bottom of the page
or
Use the DEFER attribute on SCRIPT tags (although remember this is not supported by Firefox)
Use tools to help you find any performance problems, bottlenecks:
Google PageSpeed – http://code.google.com/speed/page-speed/docs/using.html
Yahoo YSlow – http://developer.yahoo.com/yslow/
The ramblings of Jon Reed. I am Developer at an international news corporation. Everyday I work with various technologies such as PHP, MySql, CSS, XHTML. I Love Web Development.
1 Response to JavaScript Loading & Page Performance
Mike Pearce
June 1st, 2010 at 12:15 pm
Great post mate, some advanced stuff.
What do you suggest as an alternative to document.write(). Especially if I want to write a script tag to a remote src to the page?