Leaving Scripts and Styles Inline

Posted: August 7, 2008 in ASP, News

When deciding if you should leave a Web page’s JavaScript and styles inline or move them to a separate linked .js or .css file, there are a few different factors to consider.

For most individual pages, leaving the scripts and styles inline will result in them loading quicker and rendering faster. This is because the client’s browser doesn’t need to make as many HTTP requests to the server. While it’s true that most browsers can issue multiple HTTP requests simultaneously, you still get some slow down due to network latency. Not to mention the fact that most web pages include images and other assets which the other HTTP requests could be fetching instead.

So why do developers ever move JavaScript and styles to external files? For one very simple and powerful reason — caching. Very often the same JavaScript and styles are used on many pages of a site. Since browsers can only cache complete files, by moving these elements of the page to external files, browsers are able to cache them for use on subsequent requests. While the first request might be slightly slower, this small performance hit is more then made up for by the fact that, once loaded, these external files can be retrieved from the browser’s cache and will only need to be re-loaded from the Web server once the cache expires.

So with those points in mind, when should you use inline scripts and styles and when should you link to external files? If you’re going to use something more then once, it’s usually best to place it in an external file and link to it. If the script or style in question will only be used on one page, then by all means leave it inline on that page.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s