Question

Is it possible to attempt to load a javaScript source file from an alternate location if it fails to load from the first?

For example, in the HTML file, I might have:

<script type="text/javascript" src="http://domain.com/javascript_file.js"></script>

But if that fails to load, I could try to load the file from this second place instead:

<script src="directory/javascript_file.js" type="text/javascript"></script>

Thanks!

Was it helpful?

Solution

I recommend you use yepnope.js for doing this. Here's an example using jQuery:

yepnope({
  load: 'http:/­/ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js',
  complete: function () {
    if (!window.jQuery) {
      yepnope('local/jquery.min.js');
    }
  }
});

You'll just have to ensure you have some way of detecting the failure to load your external file.

OTHER TIPS

It's possible.

I'd probably approach it like this:

First, create a function to load scripts.

function loadScript(src) {
    var s = document.createElement('script'), x;
    s.type = 'text/javascript';
    s.async = true;
    s.src = src;
    x = document.getElementsByTagName('script')[0]; 
    x.parentNode.insertBefore(x, s);
}

That's good enough for loading scripts, but how do we know when it finished loading, or didn't load at all?

Let's add two callback parameters (one for success and one for failure) and a timeout parameter. We'll also need to attach an event listener to our script element to fire the callbacks when it loads.

function loadScript(src, onSuccess, onFail, timeout) {
    var s = document.createElement('script'), x, loaded;
    s.type = 'text/javascript';
    s.async = true;
    s.src = src;

    s.onload = s.onreadystatechange = function() {
        if (''+s.readyState).match(/^(|complete|loaded|uninitialized)$/) {
            loaded = true;
            onSuccess && onSuccess();
            s.onload = s.onreadystatechange = null;
        }
    }

    if (onFail) {
        setTimeout(function(){loaded || onFail();}, timeout || 5000);
    }

    x = document.getElementsByTagName('script')[0]; 
    x.parentNode.insertBefore(x, s);
}

Full disclosure:

  • This is completely untested.
  • The first block of code is ripped off from Google Analytics, with slightly less ugly code.
  • The second block of code is ripped off from yepnope after seeing Slace's answer, with slightly uglier, but more terse, code.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top