Home  >  Article  >  Web Front-end  >  javascript dynamic script addition

javascript dynamic script addition

高洛峰
高洛峰Original
2016-10-12 11:40:131097browse

异步加载js文件或者异步加载js模块,支持所有浏览器,包括IE,参考至javascript高级编程

1.createScript方法用于创建一个script标签并添加到body标签中

2.createModule方法用于创建一个script脚本的标签,并且如果在IE8以下的版本运行会抛出异常,在异常捕获模块中执行script.text兼容IE添加js的脚本内容。

<button id="demo">js文件</button>
    <button id="demo1">js模块</button>
    <script type="text/javascript">
        //异步加载文件,支持所有浏览器
        document.getElementById("demo").onclick = function () {
            createScript("../../js/jquery-1.8.3.min.js");
        }

        function createScript(url) {
            var script = document.createElement("script");
            script.type = "text/javascript";
            script.src = url;
            document.body.appendChild(script);
        }


        //这里首先会尝试标准的DOM方法,因为除了IE(在IE中会抛出错误),所有浏览器都支持这种方法,如果抛出错误则说明是IE,于是就必须使用tezt属性了
        document.getElementById("demo1").onclick = function () {
            createModule("function sayHi(){alert(&#39;Hi !&#39;)}");
        }

        function createModule(code) {
            var script = document.createElement("script");
            script.type = "text/javascript";
            try {
                script.appendChild(document.createTextNode(code));
            } catch (ex) {
                script.text(code);
            }
            document.body.appendChild(script);
        }
    </script>


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn