ruby-on-rails-4modernizrpolyfillsyepnope

How to load a conditional js file using modernizr now that yepnope is deprecated?


What are some good practices for loading a conditional javascript file using modernizr now that yepnope and .load are deprecated in the latest version of modernizr.

Used to be able to use the .load function. http://modernizr.com/docs/#load

Modernizr.load({
  test: Modernizr.geolocation,
  yep : 'geo.js',
  nope: 'geo-polyfill.js'
});

Now .load is deprecated along with yepnope. https://github.com/SlexAxton/yepnope.js/

Reference for answer prior to yepnope being deprecated Loading Scripts Using Modernizr... Not Working


Solution

  • You can use jQuery's getScript method. I think you could also use .fail instead of the else statement. Spent my morning figuring this out and have been trying to answer these to save people some time!

    Something like this?

    if (Modernizr.geolocation) {
        jQuery.getScript("geo.js")
            //it worked! do something!
            .done(function(){
                console.log('geo.js loaded');
            });
    } else {
        jQuery.getScript("geo-polyfill.js")
            //it worked! do something!
            .done(function(){
                console.log('geo-polyfill.js loaded');
            });
    }