Loading Page Styles And JavaScript With JavaScript

2nd July 2008 - 3 minutes read time

One good technique when using JavaScript is to load a single JavaScript file and get this file to load any other JavaScript or CSS documents that are needed. This means that you can simplify the instillation of a script on a page by including a single file, which then loads everything else it needs. Here is how to accomplish such a task.

The basic idea is that you add the references you need to the DOM structure of the document. Let's say that we want to load a CSS file called styles.css. To do this at run time we need to create a element and give it some parameters before adding it onto the end of the

element of the page. Here is the code needed to do this.
  1. // create the link element and store it in a variable.
  2. var linkElement = document.createElement("link");
  3. // set the rel attribute of the link element to be stylesheet
  4. linkElement.setAttribute("rel", "stylesheet");
  5. // set the type attribute of the link element to be text/css
  6. linkElement.setAttribute("type", "text/css");
  7. // set the href attribute of the link element to point to the file
  8. linkElement.setAttribute("href", "http://www.example.com/styles.css");
  9. // add the link element to the head of the document.
  10. document.getElementsByTagName("head")[0].appendChild(linkElement);

To do the same thing with JavaScript we just need to change the element and attributes a little. Here is how to load a script file called script.js.

  1. var scriptElement = document.createElement("script");
  2. scriptElement.setAttribute("type","text/javascript");
  3. scriptElement.setAttribute("src","http://www.example.com/script.js");
  4. document.getElementsByTagName("head")[0].appendChild(scriptElement);

You can also streamline this process by creating a function that takes the filename and what sort of file we are trying to load.

  1. function loadjscssfile(filename, filetype){
  2. if (filetype=="js"){
  3. //if filename is a external JavaScript file
  4. var theElement = document.createElement("script");
  5. theElement.setAttribute("type","text/javascript");
  6. theElement.setAttribute("src", filename);
  7. }else if(filetype=="css"){
  8. //if filename is an external CSS file
  9. var theElement= document.createElement("link");
  10. theElement.setAttribute("rel", "stylesheet");
  11. theElement.setAttribute("type", "text/css");
  12. theElement.setAttribute("href", filename);
  13. }
  14. if (typeof element!="undefined"){
  15. document.getElementsByTagName("head")[0].appendChild(theElement);
  16. }
  17. };

To use this function do the following.


One final note is that the file name must be absolute reference to the file. The rule is, if you can't cut and paste the URL into your browser and get the file then this method isn't going to work.

Add new comment

The content of this field is kept private and will not be shown publicly.