JS Coding Questions Logo
JS Coding Questions
#295💼 Interview💻 Code

How do you load CSS and JS files dynamically

Advertisement

728x90

You can create both link and script elements in the DOM and append them as child to head tag. Let's create a function to add script and style resources as below,

javascript
1function loadAssets(filename, filetype) {
2  if (filetype == "css") {
3  // External CSS file
4  var fileReference = document.createElement("link");
5  fileReference.setAttribute("rel", "stylesheet");
6  fileReference.setAttribute("type", "text/css");
7  fileReference.setAttribute("href", filename);
8  } else if (filetype == "js") {
9  // External JavaScript file
10  var fileReference = document.createElement("script");
11  fileReference.setAttribute("type", "text/javascript");
12  fileReference.setAttribute("src", filename);
13  }
14  if (typeof fileReference != "undefined")
15  document.getElementsByTagName("head")[0].appendChild(fileReference);
16  }

Advertisement

Responsive Ad
🎯 Practice NowRelated Challenge

JavaScript Coding Exercise 39

Test your knowledge with this interactive coding challenge.

Start Coding

Advertisement

728x90
295of476