How to load CSS and JS files dynamically ?
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.
For the dynamic file loading,
- We create the required element using document.createElement( <element name>)
- Then we define/assign the attributes like the script.src and script.type.
- We append the element to the head using document.getElementsByTagName(‘head’).append( <element variable>)
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.
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.
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.
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.
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.