如何删除已加载的脚本并添加新脚本? [英] How to remove loaded script and add new script?

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

问题描述

我正在创建一个演示,其中在URL中添加了查询字符串.当我加载HTML时,我得到了查询的值.我希望这样,如果查询字符串的值为"simple",它将删除已加载的JS文件.

I am creating a demo in which I have added a query string in the URL. When I load my HTML I get the value of my query. I want it so that if the query string has the value "simple", it removes the JS file that is loaded.

如果找到的值不是"simple",则应加载另一个JS文件.

If it finds a value other than "simple" it should load another JS file.

我在Google上搜索了解决方案,但没有任何效果.

I Google searched it for solution, but nothing works.

这是我的HTML:

<!DOCTYPE html>
<html>
<head>
    <script src="js/jquery-1.11.0.min.js" type="text/javascript"></script>
    <script src="js/copynode.js" type="text/javascript" id="dynamic_files"></script>
<script type="text/javascript">

    $(window).load(function(){
        // full load
        var query = decodeURIComponent(window.location.search.substring(1));
        console.log("---------------------");
        var index=query.indexOf("=")
        query=query.substr(index+1,query.length);
        console.log(query);
        if(query=="simple"){
       alert('if--');
            //$('#dynamic_files').remove();
        }else{
            alert('else--');
            $('#dynamic_files').remove();
            var script = document.createElement('script');
            script.src = 'js/index.js';
            document.getElementsByTagName('div')[0].appendChild(script);
        }

    });

</script>
</head>

<body >
    <h1>My Web Page</h1>
    <p id="demo">A Paragraph.</p>
    <button type="button" onclick="loadScript()">Load Script</button>
</body>
</html> 

推荐答案

您可以先检查String的值,然后编写如下函数:

you can check the value of the String first then write a function like :

function checkString(){
 if($('#ID_OF_ELEMENT_OF_THE_STRING').value == "simple"){
    //load the script needed
    var head = document.getElementsByTagName('head').item(0);
    var script = document.createElement('script');
    script.setAttribute('type', 'text/javascript');
    script.setAttribute('src', 'http://mysite/my.js');
    head.appendChild(script);
 }else{
    //load the other part.
 }

}

这篇关于如何删除已加载的脚本并添加新脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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