简体   繁体   English

Javascript 动态脚本加载 IE 问题

[英]Javascript Dynamic Script Loading IE problems

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

I need to launch crtGridRicPrdo() function when the page starts, and in FireFox all works fine but in Internet Explorer I have a problems!我需要在页面启动时启动 crtGridRicPrdo() function,在 FireFox 中一切正常,但在 Internet Explorer 中我有问题!

Internet explorer does not support "onload" on script tags, instead it offers the "onreadystatechange" (similarly to an xhr object). Internet Explorer 不支持脚本标签上的“onload”,而是提供“onreadystatechange”(类似于 xhr 对象)。 You can check its state in this way:你可以这样检查它的state:

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

otherwise you can call crtGridRicProd() at the end of your js file否则您可以在 js 文件末尾调用crtGridRicProd()

EDIT编辑

example:例子:

test.js:测试.js:

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

index.html:索引.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!您将在两个浏览器中看到警报!

I use the following to load scripts one after another ( async=false ):我使用以下内容一个接一个地加载脚本( async=false ):

var loadScript = function(scriptUrl, afterCallback) {
            var firstScriptElement = document.getElementsByTagName('script')[0]; 
    var scriptElement = document.createElement('script');
            scriptElement.type = 'text/javascript';
            scriptElement.async = false;
            scriptElement.src = scriptUrl;

    var ieLoadBugFix = function (scriptElement, callback) {
        if ( scriptElement.readyState == 'loaded' || scriptElement.readyState == 'complete' ) {
            callback();
        } else {
            setTimeout(function() { ieLoadBugFix(scriptElement, callback); }, 100);
        }
    }

    if ( typeof afterCallback === "function" ) {
        if ( typeof scriptElement.addEventListener !== "undefined" ) {
            scriptElement.addEventListener("load", afterCallback, false)
        } else {
            scriptElement.onreadystatechange = function(){
                scriptElement.onreadystatechange = null;
                ieLoadBugFix(scriptElement, afterCallback);
            }
        }
    }
    firstScriptElement.parentNode.insertBefore(scriptElement, firstScriptElement);
}

Use it like this:像这样使用它:

loadScript('url/to/the/first/script.js', function() {
    loadScript('url/to/the/second/script.js', function() {
    // after both scripts are loaded
    });
});

One bugfix which the script includes is the latency bug for IE.该脚本包含的一个错误修复是 IE 的延迟错误。

For proberly dynamic loading a js-script (or css-file) in IE you must carefully check the path to the loaded file!为了在 IE 中动态加载 js 脚本(或 css 文件),您必须仔细检查加载文件的路径! The path should start from ' / ' or ' ./ '.路径应从“ / ”或“ ./ ”开始。

Be aware, that IE sometimes loses leading slash - as for instance is described here: https://olgastattest.blogspot.com/2017/08/javascript-ie.html请注意,IE 有时会丢失前导斜杠 - 例如此处所述: https://olgastattest.blogspot.com/2017/08/javascript-ie.html

You are loading script from external source.您正在从外部源加载脚本。 So you need to wait until it loads.所以你需要等到它加载。 You can call your function after id completed. id 完成后,您可以致电您的 function。

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

function scriptLoaded(){
// do your work here
}

When I red your code, I figured out that you try to append an onload event to the script tag.当我红色你的代码时,我发现你试图 append 一个 onload 事件到脚本标签。

<html>
 <head>
  <script type="text/javascript" onLoad="crtGridRicPrdo()">
   ...
  </script>
 </head>
 <body>
  ...
 </body>
</html>

This will be the result of your javascript code.这将是您的 javascript 代码的结果。 Why don't you add it to the body tag?为什么不将它添加到body标签? This is the classic way and will defnatly work under IE too.这是经典的方式,也可以在 IE 下工作。 This will also reduce your code:这也将减少您的代码:

var bodyID = document.getElementsByTagName("body")[0];
bodyID.setAttribute("onload", "crtGridRicProd();");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM