开发者

IE intermittently doesn't execute a dynamically added script file

开发者 https://www.devze.com 2022-12-20 00:48 出处:网络
We have some J开发者_StackOverflow社区avaScript that writes a script include to a dynamic resource in our web page in order to allow us to communicate some information between pages served from differ

We have some J开发者_StackOverflow社区avaScript that writes a script include to a dynamic resource in our web page in order to allow us to communicate some information between pages served from different servers that are subject to cross site scripting restrictions.

The idea is that the browser requests the JavaScript file which is served by a dynamic resource on the server side (which also puts some server side information into the Request). The JavaScript file is then executed by the browser when it is added to the page.

We've run into an issue with Internet Explorer where the JavaScript returned in the response is intermittently not executed when it is added to the page. Inspecting a Fiddler HTTP trace when the problem occurs shows the script is successfully returned to the browser.

To test this more reliably, I altered the code that adds the script to run 1000 times in a loop as below:

for (var i = 1; i <= 1000; i++) {
    try {
        var script = document.createElement("SCRIPT");
        script.src = serverHome + "/ajavascriptfile.js?token=" + token + "&num=" + i;
        script.id = token;
        document.getElementsByTagName("HEAD")[0].appendChild( script );
    } catch (e) {
        alert(e);
    }
}

The script returned by ajavascriptfile.js simply increments a counter on my page:

var output = document.getElementById("output");
output.innerHTML = parseInt(output.innerHTML) + 1;

No exceptions are ever caught or alerted in this test.

If this executes properly the counter should get to 1000 (which it does in Firefox). However in IE6 it averages 900-950, IE7 is around 995-998 and IE8 is a shocking 750-800.

Has anyone else encountered Internet Explorer not executing dynamically included scripts? If so, do you know how to workaround this problem?


It may be that the scripts are not queueing in the order they are added to the head, but are being interpreted as soon as they're activestate is complete, either from the cache or a download. If the script you asked for last loads first, it can cause a problem.

IE8 allows 6 concurrent scripts, I think IE7 allowed 4, and 6 allowed 2.

I have seen this in Opera, Chrome and Safari as well, (but not firefox yet) so if I am loading more than one script, I hold running any commands until I know the resources are available- usually by testing the typeof a function from the required file, and a timer callback if not found.


Internet Explorer may be caching the script file. Try adding some additional entropy to the src include:

script.src = serverHome + "/ajavascriptfile.js?token=" + token + "&num=" + i + '&r=' + Math.random();
0

精彩评论

暂无评论...
验证码 换一张
取 消