Webmaster Time Savers - External Javascript

If you have javascript code that runs on multiple pages of your website you should consider moving the javascript into external files. The reasons for moving your common code is similar to why you should move your style sheet information into external files.

The benefits of using an external style sheet include:

  • Simplifies Maintenance
    If your javascript code controls something that you do on many pages of your website instead of having to edit every page that needs the javascript code, only have to edit the one javascript file to make the change on all the pages of your website that use that code.

  • Bandwidth
    External javascript files can be cached by web browsers for use on multiple pages of your website saving you bandwidth.

  • Website Speed
    Because the javascript file can be cached visits to other pages in your website will be faster because the web browser does not need to download the javascript file again.

How To Use an External Javascript File

The first step in creating an external javascript file is to create a new text document in your favorite text editor. You can then copy the code out of your web page and paste it in your new document. For example we have this simple script that creates an alert box when the page loads:

Copy the section “alert(‘Hello World’);” out of the web page and paste it into the new text document you created and save it with a .js extension. In this case alert.js. It needs to be accessible to the web page that needs it so you could place it on the same folder or in a sub folder.

You then need to edit the javascript tag on the web page to load the external javascript file. When you are done the code on the web page should look like this:

The src attribute in the script tag tells the page where it should look for the alert.js file. If you placed it in a sub folder you would change it to src=“folder/alert.js”. If you have problems with the script not working, check your path first to make sure you are loading the file.

You can now make the change to all the pages that need that javascript. If you decide in the future to make the javascript do more you just have to edit your alert.js file and the change will take place on all the pages that use the file. What a great time saver.

Categories: web-programming