Open In App

How to load CSS and JS files dynamically ?

Improve
Improve
Like Article
Like
Save
Share
Report

Generally, the CSS and JS files are included statically with HTML code. It means they are written in the script or the link tag in the  HTML code. But this slows down the execution as a bulk of code is loaded unnecessarily. It may or may not use the functionality related to that DOM element. So dynamically, we load the CSS and JS files during the runtime when we need their functionality.

Load CSS and JS files dynamically: We create a script element for the JS file and link element for the CSS file as required using DOM, assign the appropriate attributes to them, and then add the element to the desired location within the document tree using the element.append() method.

Let us see in detail the whole process through a small project, step by step.

Step 1: Create an index.html file and app.js file. This would be our HTML file through which we will demonstrate dynamically loading of JS and CSS files. The app.js file would contain the functionality to call dynamically loading of the files. We would add it statically in our HTML file. 

In our HTML file, we have created two divs inside an HTML div. The upper HTML div contains a heading and a button to show messages. The functionality to show messages would be added dynamically. Initially, the button would not work. In the lower div, we have two buttons, one for loading the CSS file and the other for the JS file dynamically. The onClick functions for these buttons are defined in the app.js file. 

File structure:

File Stucture

index.html




<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible"
          content="IE=edge">
    <meta name="viewport" 
          content="width=device-width, initial-scale=1.0">
    <title>Dynamic</title>
    
     <!-- the static loading of app.js file-->
    <script src="app.js"></script>
</head>
<body>
      
    <div>
        <div id="upper">
            
            <!-- The message will change on successful
                 execution of View button-->
            <h3 id="mssg">
               We are here to learn how to load
               CSS and JS file dynamically
            </h3>
  
            <!-- The message() function is in script.js file -->
            <button onclick="message()"> View Message </button>
        </div>
        <br>
        
        <!-- This div would disappear after view 
             message is successfully executed-->
        <div id="lower">  
            
            <!-- The loadCSS would load the styles.css file -->
            <button onclick="loadCSS()">
              Load CSS 
            </button>
  
            <!-- The loadJS would load the script.js file-->
            <button onclick="loadJS()">
              Load JS 
            </button>            
        </div>
    </div>
</body>
</html>


In the app.js file, we have two functions loadJS() and loadCSS() which are onClick attributes of the two buttons defined in the lower HTML div in the HTML file. 

For the dynamic file loading,

The practical implementation of the above steps is shown below in the code. We also use the indexOf() method of string to check that we repeatedly don’t add the same file on multiple clicking of the button.

 

app.js




// The string stores the name of files added till now
var filesAdded = ''
  
// For loading JS file
function loadJS(){ 
  
    // Gives -1 when the given input is not in the string
    // i.e this file has not been added
      
    if(filesAdded.indexOf('script.js') !== -1)
        return
          
    // Head tag
    var head = document.getElementsByTagName('head')[0] 
      
    // Creating script element
    var script = document.createElement('script'
    script.src = 'script.js'
    script.type = 'text/javascript'
      
    // Adding script element
    head.append(script) 
      
     // Adding the name of the file to keep record
    filesAdded += ' script.js'
}
  
// To load CSS file
function loadCSS() { 
  
    if(filesAdded.indexOf('styles.css') !== -1)
        return
  
    var head = document.getElementsByTagName('head')[0]
      
    // Creating link element
    var style = document.createElement('link'
    style.href = 'styles.css'
    style.type = 'text/css'
    style.rel = 'stylesheet'
    head.append(style);
      
    // Adding the name of the file to keep record
    filesAdded += ' styles.css' 
}


Step 2: Now create a styles.css file, which would be loaded dynamically. This file contains the code to provide border, margin, padding, and background-color to the two HTML divs separately using their ids.

styles.css




#upper{
    border: 2px solid red;
    margin: 10px;
    padding: 15px;
    background-color: aqua;
    align-items: center;
}
  
#lower{
    border: 2px solid green;
    margin: 10px;
    padding: 15px;
    background-color: greenyellow;
    align-items: center;
}


Step 3: Now we would create a script.js file that would display a message by editing the h3 element on clicking of View Message button, and disappearing the lower div, or changing its display property to none. This JS file would be loaded dynamically.

script.js




function message() {
  
    // Get the h3 element
    var h3 = document.getElementById('mssg'
  
    // Changed it's text, colour
    h3.innerText = 'CONGRATS!! You have learnt
    h3.style.color = 'red
      
    // Get the lower div
    var div = document.getElementById('lower')
  
    // Disappear mode
    div.style.display = 'none' 
}


Step 4: Now copy the full path of the index.html file and load it in your browser. Initially, the View Message labeled button would give the error. When you click the load CSS button then styling would appear and after clicking the load JS button, the View message button would become functional.

Output:

So this is how you can handle the dynamic loading of files using DOM Manipulation. It is very useful as increases speed and provides robustness.



Last Updated : 08 Dec, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads