Javascript动态脚本加载IE问题 [英] Javascript Dynamic Script Loading IE problems

查看:45
本文介绍了Javascript动态脚本加载IE问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下代码动态加载脚本:

I'm trying to load dynamically script with this code:

var headID = document.getElementsByTagName("head")[0]; 
var script = document.createElement('script'); 
script.type='text/javascript'; 
script.src="js/ordini/ImmOrd.js"; 
script.setAttribute("onload", "crtGridRicProd();");                       
headID.appendChild(script);

页面启动时,我需要启动crtGridRicPrdo()函数,并且在FireFox中一切正常,但是在Internet Explorer中,我遇到了问题!

I need to launch crtGridRicPrdo() function when the page starts, and in FireFox all works fine but in Internet Explorer I have a problems!

推荐答案

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!

这篇关于Javascript动态脚本加载IE问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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