0

I'm loading lightbox2 via the following CDN //cdnjs.cloudflare.com/ajax/libs/lightbox2/2.7.1/js/lightbox.min.js

if this is unavailable then I want to fallback to my core files. How do I check to see if lightbox has already been defined so as to avoid loading my core files.

I tried typeof lightbox === "undefined" but that always returns true forcing my core files to be loaded.

I have fallbacks for jquery, angular etc already - it is lightbox2 that I am having issues with checking if it has already been loaded.

neilakapete
  • 1,098
  • 1
  • 7
  • 11
  • Have a look at this [SO question](http://stackoverflow.com/questions/5257923/how-to-load-local-script-files-as-fallback-in-cases-where-cdn-are-blocked-unavai). Maybe that helps. – AWolf Dec 17 '14 at 20:21
  • it is the actual checking to see if lightbox2 is available that I am having trouble with. – neilakapete Dec 18 '14 at 21:13

1 Answers1

1

Yes, the problem here is that there is nothing in global scope because lightbox doesn't add anything to it. (see this SO question). That's why you can't test it like window.lightbox.

A workaround is to load the script with an ajax request like in the demo below. The getScript method is a shorthand Ajax function (see here for details).

There you have a fail callback where you can add your local script to the DOM if loading of the cdn fails.

You can do the same for any file that you're loading from a cdn (e.g. the stylesheet of lightbox).

var addLocalScript = function (src) {
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = src; // use this for linked script
    //script.text = "alert('voila!');" // use this for inline script
    document.body.appendChild(script);
};

$(function () {
    var url = 'https://cdnjs.cloudflare.com/ajax/libs/lightbox2/2.7.1/js/lightbox.min.js';

    $.getScript(url)
        .done(function (script, textStatus) {
        console.log(textStatus);
    })
        .fail(function (jqxhr, settings, exception) {
        console.log('cdn load failed');
        //add local script
        addLocalScript('js/lightbox/lightbox.min.js');
    });
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/lightbox2/2.7.1/css/lightbox.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="http://lorempixel.com/400/200" data-lightbox="image-1" data-title="My caption"><img src="http://lorempixel.com/400/200"/></a>
Community
  • 1
  • 1
AWolf
  • 8,770
  • 5
  • 33
  • 39