Home

How to programmatically request additional JS and CSS files with vanilla JS

There are times when we want to dynamically request additional .css and .js files in our web applications.

With the broad adoption of JavaScript frameworks like React, Angular and Vue, we often forget how to do this rather simple task.

Bellow is your copy and pasta. Bon appétit!

Short example

// requesting a new `.js` file
const scriptElement = document.createElement('script');
scriptElement.setAttribute('src', 'imported.js');
document.body.appendChild(scriptElement);

// requesting a new `.css` file
const styleElement = document.createElement('link');
styleElement.setAttribute('rel', 'stylesheet');
styleElement.setAttribute('href', 'imported.css');
document.head.appendChild(styleElement);

Full working example

Place all four files bellow under the same folder.

index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Import js and css dynamically</title>
  </head>
  <body>
    <p>
      Hello World
    </p>

    <script src="main.js"></script>
  </body>
</html>

main.js
const scriptElement = document.createElement('script');
scriptElement.setAttribute('src', 'imported.js');
document.body.appendChild(scriptElement);

const styleElement = document.createElement('link');
styleElement.setAttribute('rel', 'stylesheet');
styleElement.setAttribute('href', 'imported.css');
document.head.appendChild(styleElement);

imported.css
p {
  color: red;
}

imported.js
window.alert('Hello imported JS!');