Dynamically include script and CSS file with JavaScript

Mainly the external script or CSS files are added in the <head> section or at the end of the <body> section.

The included script or CSS files take the time to load and it may slow down your site if they are more in numbers.

With the use of JavaScript, you can dynamically add external file reference in your page on the Client side.

Dynamically include script and CSS file with JavaScript


Contents

  1. Include script file
  2. Include CSS file
  3. Conclusion

 


 

1. Include script file

Here, I create a new function addScript() which takes script file name as a parameter.

Within the function creating a new element of type script and use the file name to define src attribute.

Select <head> using document.getElementsByTagName('head')[0] and with append() add the newly created element at the end of the <head>.

Completed Code

addScript('script.js');

// Include script file
function addScript(filename){
 var head = document.getElementsByTagName('head')[0];

 var script = document.createElement('script');
 script.src = filename;
 script.type = 'text/javascript';

 head.append(script);
}

 

2. Include CSS file

Created a new addCSS() function which also takes the filename as a parameter.

Working of this function is similar to above function the only difference is – defining a link type of element instead of a script.

Use the file name to define element href attribute and define other attributes which are required.

Completed Code

addCSS('style.css');

// Include CSS file
function addCSS(filename){
 var head = document.getElementsByTagName('head')[0];

 var style = document.createElement('link');
 style.href = filename;
 style.type = 'text/css';
 style.rel = 'stylesheet';
 head.append(style);
}

 

3. Conclusion

You can use the above code to include file only when its required within the web page.

For this, you have to create a script or link type element and initialize required attributes.

After successfully creating add the new element in the <head> section.

Related Post

Spread the love

2 Comments

  1. Ankita said:

    Hi,

    Nice article. But it leave me wondering about security loopholes it might introduce. What are your thoughts on that?

    February 28, 2017
    Reply
    • Yogesh Singh said:

      You can use the server-side scripting language to conditionally include the script or CSS file.

      February 28, 2017
      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *