2

I have to do the cross-domain ajax,so I try the jsonp.

Then I will have to add the script element dynamiclly to the page,however I can not check its status.

In firefox/chrome/ie8+ I can use the

script.onLoad=function(){}
script.onError=function(){}

Also I tried

script.onreadystatechange=function(){}

in ie<8.

But it does not work in ie<8.

How to make it work?

BTW,I want to make it using the native javascript,so do not tell me using the jQuery or anything else.


update:

In fact,the script I request from server is not a library,it is just one-line javascript code (the jsonp). So I can not using the timer to check.

doydoy44
  • 5,720
  • 4
  • 29
  • 45
hguser
  • 35,079
  • 54
  • 159
  • 293

3 Answers3

2

Looking at yepnope.js it uses both onload and onreadystatechange but it also uses a timeout loop to check the readystate property of the script element, see here.

Aaron Powell
  • 24,927
  • 18
  • 98
  • 150
2

For IE, think of alternate ways to check load has happened, e.g. in your script file add the line

script_myScriptUniqueName_loaded = true;

and then in the dynamic add, if script.onload is not null (before setting a callback) use window.setInterval to check for existance of script_myScriptUniqueName_loaded, with a timeout to throw error, and if exists call callback.
Remember to do window.clearInterval when you're done.

Paul S.
  • 64,864
  • 9
  • 122
  • 138
1

The load event for script elements was introduced in HTML5, prior to that it was only available for frameset and body elements (though most browsers also implemented it for img elements too). So if you want to support earlier browsers you'll need to be creative.

One solution is to put a function call at the top of the script to say that the script has been loaded, as the browser should not execute any code in the script until it's loaded in its entirety.

Another is to insert a second script with the "I'm loaded" function or flag immediately after the first in the presumption that the second will not be executed until the first has been loaded and executed.

RobG
  • 142,382
  • 31
  • 172
  • 209