How to Add or Remove the javascript file using javascript function

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

01function AddJsFile(file) {
02var script  = document.createElement('script');
03script.src  = file;
04script.type = 'text/javascript';
05script.defer = true;
06 
07document.getElementsByTagName('head').item(0).appendChild(script);
08}
09 
10Or We can use this also, both will work:
11function AddJsFile(file)
12{
13document.write('');
14}

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

1function AddCssFile(file) {
2var stylesheet  = document.createElement('link');
3stylesheet.href  = file;
4stylesheet.type = 'text/css';
5stylesheet.defer = true;
6 
7document.getElementsByTagName('head').item(0).appendChild(stylesheet);
8}

Or We can use this also, both will work:

1function AddCssFile(file)
2{
3document.write('');
4}

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

1function RemoveJsFile(file) {
2var alljs = document.getElementsByTagName("js")
3for (var i = alljs.length; i >= 0; i--) {
4if (alljs[i] && alljs[i].getAttribute("src")!= null && alljs[i].getAttribute("src").indexOf(file)!=-1)
5 
6alljs[i].parentNode.removeChild(alljs[i])
7}
8 
9}

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

1function RemoveCssFile(file) {
2var allcss = document.getElementsByTagName("css")
3for (var i = alljs.length; i >= 0; i--) {
4if (allcss[i] && allcss[i].getAttribute("href")!= null && allcss[i].getAttribute("href").indexOf(file)!=-1)
5 
6allcss[i].parentNode.removeChild(allcss[i])
7}
8 
9}

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.