tags:

views:

45

answers:

3

Hi,

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 beforeSend 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.

+4  A: 

jQuery has getScript

jQuery.getScript( url, [ success(data, textStatus) ] )
epascarello
But getScript has no onError-Handler. So there is no way to inform the user hat the initialize has failed.
Biggie
@Biggie "So there is no way to inform the user hat the initialize has failed." How about `textStatus`?
epascarello
Hm, if the requested file does not exist the success-function is not called (FireFox). Moreover the FireFox-log always shows an error like "malformed code" although the code works without problems.
Biggie
A: 

@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.

Pekka
A: 

error on'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 */ });
Nick Craver