Search code examples
javascripthtmlfallback

Look for a Javascript source file in a second location if the first fails to load


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!


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.