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 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 references to 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 a 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 that also takes the filename as a parameter.

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

Use the file name to define an element href attribute and define other attributes that 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 files only when it is 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.

If you found this tutorial helpful then don't forget to share.