9. Make JavaScript and CSS External

Using external files in the real world generally produces faster pages because the JavaScript and CSS files are cached by the browser. JavaScript and CSS that are inlined in HTML documents get downloaded every time the HTML document is requested. This reduces the number of HTTP requests that are needed, but increases the size of the HTML document. On the other hand, if the JavaScript and CSS are in external files cached by the browser, the size of the HTML document is reduced without increasing the number of HTTP requests..

The objective as stated below:

  • To produce faster pages as the JS and CSS files are cached by the browser

  • If cached by browser, the size of the HTML document is reduced without increasing the number of requests

  • It's much easier to reuse the CSS code if you have it in a separate file. Instead of typing the same CSS code on every web page you have, simply have many pages refer to a single CSS file with the "link" tag.
Including large JavaScripts directly into the web page has two problems.

Firstly, it will affect the ranking of your page with the various search engines since the Javascript forms part of the page content which therefore lowers the frequency on your page of the key phrases which identify what your page is about.

It also makes it much harder to reuse the same Javascript on multiple pages on your web site as the code would need to be copied to each page and so would any changes made to the script.

Example:

For example, if the following script is on our page we would select and copy the part in bold paste it into new file and name as .js file as hello.js:

< script type="text/javascript" > var hello = 'Hello World'; document.write(hello); < /script >

Our example will now look like this:

< script type="text/javascript" src="hello.js" > < /script >

The src attribute identifies to the browser both that the Javascript code is to be read from an external file (ignoring the content between the script tags if there is any) and also the name and location of the file that containsd the script (in this example - hello.js).