如何动态添加和删除js文件 [英] How to add and remove js files dynamically

查看:132
本文介绍了如何动态添加和删除js文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个网页index.php,我想添加和删除JS文件到这个页面动态



到目前为止,我做了

 < script type =text / javascriptsrc =id =dynamic_files>< / script> 

我已经计划通过


$更改此脚本标签的src b $ b

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

包含的js文件中包含脚本标签:

  document.write('< script type =text / javascriptsrc =include / js / profile1.js>< / script>'); 
document.write('< script type =text / javascriptsrc =include / js / profile2.js>< / script>');
document.write('< script type =text / javascriptsrc =include / js / profile3.js>< / script>');
document.write('< script type =text / javascriptsrc =include / js / profile4.js>< / script>'); -

我的问题是,



将该脚本标签打印到我的文档页面中,如果是这样我该如何删除它



参考:动态js文件

解决方案

你不能做document.write加载后



看这里:





您会注意到您的页面将被擦除。



它不你使用哪种方法来插入脚本,你需要阻止他们使用document.write或者用自定义方法替换document.write。



也许你想使用像 require.js 这样的东西,这是一个javascript加载器(感谢Jared比
更好的链接< a href =https://developers.google.com/loader/ =nofollow noreferrer> https://developers.google.com/loader/ )


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

解决方案

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/ )

这篇关于如何动态添加和删除js文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆