How to add and remove js files dynamically

两盒软妹~` 提交于 2019-12-13 15:49:06

问题


I have a web page index.php, I want to add and remove JS files to this page dynamically

So far I did,

<script type="text/javascript" src="" id="dynamic_files"></script>

I had planned to change the src of this script tag by

function loadJsfiles( filename ){ 
    var filePath = 'include/js/'+filename;
    $("script#dynamic_files").attr('src',filePath);
};

and the included js file has script tags in it:

document.write('<script type="text/javascript" src="include/js/profile1.js"></script>');
document.write('<script type="text/javascript" src="include/js/profile2.js"></script>');
document.write('<script type="text/javascript" src="include/js/profile3.js"></script>');
document.write('<script type="text/javascript" src="include/js/profile4.js"></script>'); –

My question is that,

will that script tag printed in to my document page, if so how do I remove it

Reference: Dynamic js files


回答1:


You CANNOT do document.write after load

Look here:

Javascript: Run "document.write" in createElement script failed

You will notice your page will be wiped.

It does not matter which method you use to insert scripts, you need to either stop them from using document.write OR replace the document.write with a custom method.

Perhaps you want to use something like require.js - which is a javascript loader (thanks Jared for a better link than https://developers.google.com/loader/ )




回答2:


The better example is google analytics

(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();



回答3:


This is what I do:

var dynScript,dynParent;

function createjsfile(filename) {
    var fileref = document.createElement('script');
    fileref.setAttribute("type", "text/javascript");
    fileref.setAttribute("src", filename + "?noxhr="+(new Date()).getTime());
    return fileref;
}

function loadjsfile(filename){
    dynScript = createjsfile(filename);
    dynParent = document.getElementsByTagName("head")[0];
    dynParent.appendChild(dynScript);
}

function replacejsfile(filename) {
    var newelement = createjsfile(filename);
    dynParent.replaceChild(newelement, dynScript);
    dynScript = newelement;
}

On body.load event I do loadjsfile("script.js")

and when I want to reload it replacejsfile("script.js")



来源:https://stackoverflow.com/questions/10958467/how-to-add-and-remove-js-files-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!