How to Add or Remove the javascript file using javascript function

We can use following functions for adding the Javascript file dynamically.

function AddJsFile(file) {
var script  = document.createElement('script');
script.src  = file;
script.type = 'text/javascript';
script.defer = true;

document.getElementsByTagName('head').item(0).appendChild(script);
}

Or We can use this also, both will work:
function AddJsFile(file)
{
document.write('');
}

We can use following functions for adding the CSS file dynamically.


function AddCssFile(file) {
var stylesheet  = document.createElement('link');
stylesheet.href  = file;
stylesheet.type = 'text/css';
stylesheet.defer = true;

document.getElementsByTagName('head').item(0).appendChild(stylesheet);
}

Or We can use this also, both will work:

function AddCssFile(file)
{
document.write('');
}

We can use the following code for remving the JS the files.


function RemoveJsFile(file) {
var alljs = document.getElementsByTagName("js")
for (var i = alljs.length; i >= 0; i--) {
if (alljs[i] && alljs[i].getAttribute("src")!= null && alljs[i].getAttribute("src").indexOf(file)!=-1)

alljs[i].parentNode.removeChild(alljs[i])
}

}

We can use the following code for remving the CSS the files.

function RemoveCssFile(file) {
var allcss = document.getElementsByTagName("css")
for (var i = alljs.length; i >= 0; i--) {
if (allcss[i] && allcss[i].getAttribute("href")!= null && allcss[i].getAttribute("href").indexOf(file)!=-1)

allcss[i].parentNode.removeChild(allcss[i])
}

}

Published by

Purab

I am Purab from India, Software development is my profession and teaching is my passion. Programmers blog dedicated to the JAVA, Python, PHP, DevOps and Opensource Frameworks. Purab's Github Repo Youtube Chanel Video Tutorials Connect to on LinkedIn

Leave a Reply

Your email address will not be published.