i try to load a JavaScript dynamically with jQuery to initlialize my ajax-application. I want to get a handler-function called, when the script was loaded successfully. This is what my code looks like:
var $script = $('<script type="text/javascript"></script>').appendTo('head');
$script.load(function() { ... });
$script.error(function() { ... });
$script.attr('src', 'foo.js');
This works fine in FireFox, Opera, Safari and Chromium.
The onload-handler is always called after the script was loaded. But the IE (v8) does neither call the onload-handler nor the onerror-handler. So my ajax-application gets never initialized ;-)Does anyone know how to fix this problem?
Best Regards, Biggie
EDIT:
I think i got it working:$.ajax({
type: "GET",
url: options.script,
data: null,
success: function(data, textStatus) {
options.onload();
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
options.onerror();
},
beforeSend: function(xhr) {
// Fix for FireFox 3 to prevent "malformed"-message
if (xhr.overrideMimeType) {
xhr.overrideMimeType("text/plain");
}
},
dataType: "script"
});
The b开发者_C百科eforeSend
is used to prevent the malformed
-error in FireFox.
This seems to work with FireFox and IE. Both call the error-handler if the script does not exist.
jQuery has getScript
jQuery.getScript( url, [ success(data, textStatus) ] )
@epascarello's answer is probably the most convenient way to go.
Other than that:
onerror
doesn't work for script elements in IE. See detailed background in this question.
onload
is supposed to work according to the MSDN. If it really doesn't, a workaround might be to execute the function in the JS that gets embedded.
Almost 1 year later...
I made a little change in jquery source code to support correctly 404 error when calling a script.
Search in source for "jQuery.ajaxTransport( "script", function(s) {" and in the body of the function (I added before onload event) add:
[...]
// Attach error event handler
script.onerror = function(){ callback(0, "error"); };
[...]
This modification will fire the "error" callback. So you can create a fallback function for 404 error.
This is a dirty modification, but worked perfectly in most browsers that I tested (FF,Chrome,Webkit,IE7-9)
error
won't work reliably in either case, however $.getScript()
(and $.ajax()
underneath) uses onreadystatechange
as well to support IE, so you can do this:
$.getScript("foo.js", function() { /* run your app code */ });
精彩评论