且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Javascript动态脚本加载IE问题

更新时间:2023-12-04 23:34:10

Internet Explorer不支持脚本标签上的"onload",而是提供了"onreadystatechange"(类似于xhr对象).您可以通过以下方式检查其状态:

Internet explorer does not support "onload" on script tags, instead it offers the "onreadystatechange" (similarly to an xhr object). You can check its state in this way:

script.onreadystatechange = function () {
   if (this.readyState == 'complete' || this.readyState == 'loaded') {
     crtGridRicProd();
   }
};

否则,您可以在js文件末尾调用 crtGridRicProd()

otherwise you can call crtGridRicProd() at the end of your js file

编辑

示例:

test.js:

function test() {
    alert("hello world");
};

index.html:

index.html:

<!DOCTYPE html>
<html>

  <head>
    <title>test</title>
</head>
<body>
    <script>
        var head = document.getElementsByTagName("head")[0] || document.body;
        var script = document.createElement("script");

        script.src = "test.js";

        script.onreadystatechange = function () {
            if (this.readyState == 'complete' || this.readyState == 'loaded') {
                test();
            }
        };

        script.onload = function() {
            test();
        };

        head.appendChild(script);

    </script>
</body>

您将在两个浏览器中看到警报!

you will see the alert in both browser!