How to dynamically inject JS/CSS into a webpage

Introduction

Working with the new frontend tech stacks is fun, however, in some cases, it might be challenging there’s a need to host the frontend application in a different way other than the trivial one (build and push your app to any hosting provider). In this article, we’re going to demonstrate how we can inject our App CSS/JS bundles into a webpage.

Use Cases

Full source code

Let’s get started by dynamically injecting JS/CSS into a webpage

Consider you’re developing a React application, once you build the project (i.e running the command yarn build), you will get the build folder output.

How to dynamically inject JS/CSS into the webpage
How to dynamically inject JS/CSS into the webpage

Inside the build folder, you will notice the file asset-manifest.json. This file contains information about the build output in JSON object format. In the object key, we have the file name, and in the object value, we have the file path value as shown below:

{
  "main.css": "/static/css/main.eea710dd.chunk.css",
  "main.js": "/static/js/main.9581e28d.chunk.js",
  "static/css/2.faf4bc0d.chunk.css": "/static/css/2.faf4bc0d.chunk.css",
  "static/js/2.697632fd.chunk.js": "/static/js/2.697632fd.chunk.js",

  ...etc.
}

So we’re going to simulate the same thing, we will create an assets.json file, and we will include the details of two Javascript files, and one CSS file

{
  "main.script.js": "script.js",
  "secondary.js": "secondary.js",
  "main.styles.css": "styles.css"
}

That’s awesome!

Now let’s create our JS files and add a simple implementation to each one of them:

Index.js file

const firstContent = document.createElement('div');
firstContent.style.width = 'fit-content';
firstContent.style.background = 'green';
firstContent.style.color = 'white';
firstContent.style.padding = '4px';
firstContent.innerHTML = 'Content from script 1';

document.getElementById('script1-content').appendChild(firstContent);

In the file above, we’ve created an HTML div element and added a few styles to it, also we’ve injected the content Content from script 1 using the innerHTML property.

At the end, we’ve targeted the div with the id script1-content and appended the firstContent child to it.

Secondary.js file

Same as what we’ve implemented in the index.js file, we gonna create a secondary.js file and append the following implementation to it.

const secondContent = document.createElement('div');
secondContent.style.width = 'fit-content';
secondContent.style.background = 'blue';
secondContent.style.color = 'white';
secondContent.style.padding = '4px';
secondContent.style.marginTop = '10px';
secondContent.innerHTML = 'Content from script 2';

document.getElementById('script2-content').appendChild(secondContent);

index.html file

Now, let’s check our index.html file, in which we’re going to add the implementation to dynamically load and inject JS/CSS files into the webpage.

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Home</title>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width" />
  </head>
  <body>
    <nav>
      <a href="/" aria-current="page">Home</a>
      <a href="/page2.html">Other page</a>
    </nav>
    <main>
      <h1 class="h1">Home page</h1>
      <span
        >H1 Style is coming from dynamic loaded <b><i>styles.css</i></b></span
      >
      <hr />
      <div id="script1-content"></div>
      <div id="script2-content"></div>
    </main>
    <script>
      fetch('./assets.json').then(async (data) => {
        const assets = await data.json();
        console.log(assets);

        if (assets) {
          Object.keys(assets).forEach((key) => {
            if (key.includes('.js')) {
              var script = document.createElement('script');
              script.type = 'text/javascript';
              script.src = assets[key];
              document.body.appendChild(script);
            } else if (key.includes('.css')) {
              var head = document.getElementsByTagName('head')[0];
              var link = document.createElement('link');
              link.rel = 'stylesheet';
              link.type = 'text/css';
              link.href = assets[key];
              head.appendChild(link);
            }
          });
        }
      });
    </script>
  </body>
</html>

Note, we don’t have any JS/CSS files loaded using the trivial way through this file.

On lines 19 and 20, we’ve two HTML div elements, each one assigned a unique id.

In line23, this is the beginning of our implementation to load the files. The browser fetch API is being used in order to load the assets file (it can be a local or remote file). Then in line28, we are looping through the JSON object keys and checking if the key contains '.js' extension or '.css'.

In case the extension contains ‘.js’, the following logic is executed:
  1. An element of type script is created
  2. Script type is set to text/javascript
  3. Script src is set to the file path from the assets JSON object
  4. Then, we do append the script tag into the webpage body
In case the extension contains ‘.css’, the following logic is executed:
  1. Reference the head tag
  2. An element of type link is created
  3. Link rel is set to stylesheet
  4. Link type is set to text/css
  5. Link href is set to the file path from the assets JSON object
  6. Then, we do append the link tag into the webpage head

Awesome!! Now let’s test that in the browser
How to dynamically inject JS/CSS into a webpage
How to dynamically inject JS/CSS into a webpage

As shown, we can see all JS/CSS are being injected into the webpage, and they are being executed correctly.


That’s it for How to dynamically inject JS/CSS into a webpage, And as always Happy coding!!

Photo from Unsplash


Related articles

Related Posts

How to remove highcharts.com credits link

How to remove highcharts.com credits link

Highcharts is a popular JavaScript charting library that offers a wide range of interactive and customizable charts for developers. However, if you’re using the free version of…

Highcharts Place text in the center of a pie chart

Highcharts Place text in the center of a pie chart

To place text in the center of a pie chart in Highcharts, you can use the chart.renderer object to create a custom label and position it in…

Test design breakpoints using jest and react-testing-library

Test responsive design using jest and react-testing-library

Testing design breakpoints in React applications is an important aspect of front-end development. It ensures that the components look and behave as expected on different screen sizes….

Testing React-Query with Jest and React-testing-library

Testing React-Query with Jest and React-testing-library

Introduction In this article we will cover the basic usage of testing useQuery hook from tanstack/react-query library, along with how to test it using jest and react-testing-library….

Highcharts How To Change Series Color with examples

Highcharts How To Change Series Color with examples

To change the color of a series in Highcharts, there are a set of options we are going to discover in this article. Option 1: Using the…

A quick introduction to Javascript shadow DOM

A quick introduction to Javascript shadow DOM

Introduction JavaScript Shadow DOM is a powerful tool for creating isolated and reusable components in web development. It allows developers to create custom elements with their own…

Leave a Reply

%d bloggers like this: