开发者

using javascript how to overcome the document.createElement('script').onload problem for ie versions

Here i have one problem. below i create script element dynamically.. The problem is ga.onload=function() can not work in ie. other browser like ff, chrome are working correctly. but IE can't work. The code is

var ga = document.createElement('scrip开发者_JAVA技巧t'); 
ga.type = 'text/javascript';
ga.async = true;
ga.src = "../../script/jquery.hint.js";
ga.onload = function(){
    some operation here;
};
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);


You can make it work for all browsers. The problem is IE reports states unreliably, it doesn't always report complete, sometimes it just reports loaded. The following code works fine for me.

runFun = "";

var newScript = document.createElement('script');

if(document.all){
    newScript.onreadystatechange = function() {
        if (newScript.readyState == 'complete') {
            newScript.onreadystatechange = "";
            runFun = new Function("alert('here');");
        }
        else if (newScript.readyState == 'loaded') {
            newScript.onreadystatechange = "";
            runFun = new Function("alert('here');");
        }
        runFun();
    }
}
else {
    // most browsers
    newScript.onload = function() {
        var runFun = new Function("alert('here');");
        runFun();
    }
}


Try putting the onload before the src. Turns out that a lot of problems I had with this type of programmatic JS functionality erratically failing in IE7+ was due to programmer error, haha. I was having a problem with the <img> tag not calling the onload handler, when I swapped them programmatically it started magically working as I expected. #ieFAIL!


The onload event on script tags may or may not work depending on browsers.

If you are using jQuery than you can use $.getScript() function to load a javascript file and assign a callback function to it. The callback is fired when javascript code has been loaded.

If you are not using a JavaScript framework then you can still use the above mentioned code to inject the script tag inside DOM. This should work in all browsers but there is no bullet proof way to determine when the script actually loads. onload may or may not work.

From this point you can try "polling" for a symbol every few seconds. This means you use window.setInterval() function to execute a polling function every few seconds after injecting the script tag. Inside the polling function you can use the JavaScript typeof operator to see if a particular variable is undefined or not (for the above example you would check whether typeof jQuery.fn.hint is undefined or not). Once it is defined, cancel the polling function and execute that some operation.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜