Externalizing Javascript and CSS
June 11, 2009
Rob Ackerman
When building your web pages, avoid embedding CSS style and javascript within the page. Instead, put the CSS and Javascript in an external file(s). What
exactly does this mean?
CSS Another common practice is to define in-line styles for each tag on a page.
<a href="http://www.someurl.com" style="color:blue; border: solid 1px red; text-decoration:underline;">
Instead, put the style definition into a class. This makes it reusable and cuts down your code. This would yield a tag like this:
<a href="http://www.someurl.com" class="myStyle">
A comman practice is to define styles in the head region of the page using the <style> tag.
<head>
[stuff here]
<style type="text/css">
.myStyle
{ color:blue;
border: solid 1px red;
text-decoration:underline;}
</style> Instead put the style class definition into an extenal file and reference it in the head of your web page like so :
<head>
[stuff here]
<link href="externalcssfile.css" rel="stylesheet" type="text/css" />
Why on earth should you do this? Search engines tend to give more weight to the content that is closer to the top, than the content that is towards the
bottom. By putting your styles and javascripts in external files you move the actual content of your page closer to the top, therefore gaining SEO.
If nothing else it will clean up some of your html, standardize your css between all your web pages (this will save your web programmers time in the future)
and even save some of your bandwidth (your visitors only need to get your stylesheet once, rather than retrieve it for every page they hit). Assuming you have 1K worth of style declarations,
Javascript As for your javascripts, you can externalize them the same way.
<script type="text/javascript" src="yourscriptname.js"></script>