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 Capture Screenshots with Puppeteer In NodeJS

How to Capture Screenshots with Puppeteer In NodeJS

To Capture Screenshots with Puppeteer: Launch a Browser Instance Navigate to the Web Page Capture the Screenshot Introduction: Puppeteer is a powerful Node.js library that allows developers…

How to Minimize Puppeteer Browser Window To Tray

How to Minimize Puppeteer Browser Window To Tray

Puppeteer is a powerful tool for automating tasks in headless or non-headless web browsers using JavaScript. While Puppeteer is often used to perform actions within a browser,…

Intercepting Responses in Node.js with Puppeteer

Intercepting Responses in Node.js with Puppeteer

Introduction: Puppeteer is a powerful Node.js library that provides a high-level API for controlling headless Chrome or Chromium browsers. It’s widely used for web scraping, automated testing,…

Mastering React Component Re-rendering in Jest

Mastering React Component Re-rendering in Jest

In this hands-on guide, we’ll explore the art of optimizing React component re-rendering within Jest tests. By combining theory with practical coding examples, you’ll gain a deep…

Eliminating Nesting Loops in React Rendering

Eliminating Nesting Loops in React Rendering

React has ushered in a new era of web application development with its component-based structure, promoting code reusability and maintainability. But as projects evolve, achieving optimal performance…

Exploring Type and Interface Usage in TypeScript

Exploring Type and Interface Usage in TypeScript

TypeScript has gained immense popularity by bridging the gap between dynamic JavaScript and static typing. Two of its fundamental features, “Type” and “Interface,” play pivotal roles in…

Leave a Reply

%d bloggers like this: