How to load CSS and JS files dynamically ?
Last Updated :
08 Dec, 2021
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:
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.
Similar Reads
How to Dynamically Load JS inside JS?
In JavaScript, dynamically loading scripts allows the inclusion of external JavaScript files only when needed, improving performance and efficiency. Instead of using static imports, scripts can be loaded conditionally at runtime. ApproachES6 provides us with a construct import(), which provides the
2 min read
How to Load External JS Scripts Dynamically in AngularJS ?
The task is to load a JS code either from a CDN or JS file stored in the system dynamically at runtime in AngularJS i.e. JavaScript code should be loaded dynamically. For example, on a button press or on some event.Whenever we want to load the script file we would have to create an element of type â
2 min read
How to add .css file to ejs
Styling is one of the most important parts of web development as it enhances the visual appearance of a website. In today's era visual presentation of content holds immense importance. EJS, short for Embedded JavaScript offers a seamless integration of JavaScript functionality within HTML templates.
3 min read
How to build classnames dynamically in Tailwind CSS?
Popular CSS framework Tailwind CSS offers pre-defined classes for rapid web page decorating. Its ability to dynamically generate class names based on configuration parameters is one of its primary characteristics, making it simple to develop responsive layouts without using bespoke CSS styles. The g
4 min read
How to dynamically load module in React.js ?
In React JS loading of modules statically is cumbersome as it loads the modules beforehand even if it is not rendered. Some components render only when the user interacts, so in such cases, it can lead to more resource consumption. When you statically import modules, you are loading larger data than
3 min read
How to detect device and swap the CSS file ?
When creating a webpage, the most important thing is the user experience with the frontend, especially the designing part or CSS. For a smooth experience, a frontend developer needs to make the webpage responsive. As "one size doesn't fit all", a single design will not work on all devices. That's wh
2 min read
How to add CSS properties to an element dynamically using jQuery ?
In this article, we will see how to add some CSS properties dynamically using jQuery. To add CSS properties dynamically, we use css() method. The css() method is used to change the style property of the selected element. The css() method can be used in different ways. This method can also be used to
1 min read
How to load CSS files using JavaScript?
The CSS file is used to describe how HTML elements will be displayed. There are various ways to add CSS files to the HTML document. JavaScript can also be used to load a CSS file in the HTML document. Approach:Use the document.getElementsByTagName() method to get HTML head element.Create a new link
2 min read
How to dynamically create and apply CSS class in JavaScript ?
To dynamically create a CSS class and apply it to the element dynamically using JavaScript, first, we create a class and assign it to HTML elements on which we want to apply CSS property. We can use className and classList properties in JavaScript. ApproachThe className property is used to add a cla
2 min read
How to apply Dynamic Styles using Tailwind CSS?
Tailwind CSS helps you style your website easily by using simple classes. Sometimes, you might need to change these styles based on different conditions, like when a button is clicked. Below are the approaches to apply dynamic styles using Tailwind CSS:Table of ContentUsing Inline StylesUsing CSS Cu
3 min read