6

Prior to Modernizr v3, I was using yepnope.js

Modernizr.load and yepnope.js have both been deprecated. How do we conditionally call stylesheets or javascript files now?

Example that worked with Modernizr v2.5.3:

Modernizr.load({
  test: Modernizr['object-fit'],
  nope: ['./dist/scripts/object-fit.js'],
  complete: function(){
  if (!Modernizr['object-fit']) {
   jQuery(".poster img").imageScale({
   scale: "best-fill", 
   rescaleOnResize: true
   });
  }
 }
});

2 Answers 2

6

There's a new syntax and the feature names are all lowercase. You can combine that with jQuery's getScript method.

Which would look something like this:

if (Modernizr.objectfit){
    jQuery.getScript("./dist/scripts/object-fit.js")
        //it worked! do something!
        .done(function(){
            console.log('js loaded');
        })
        //it didn't work! do something!
        .fail(function(){
            console.log('js not loaded');
        });
} else {
    jQuery(".poster img").imageScale({
        scale: "best-fill", 
        rescaleOnResize: true
    });
}
2
  • Thanks a bunch @mhk! Sorry, it took so long to reply.
    – scottrod
    Apr 13, 2016 at 18:10
  • To clarify, this is what worked for me: ``` $(function(){ if (Modernizr.objectfit){ } else { $.getScript("./dist/scripts/object-fit.js", function() { $(".img-scale").imageScale({ scale: "best-fill", rescaleOnResize: true }); }); }; }); ```
    – scottrod
    Apr 20, 2016 at 21:50
0

Have a look here for scripts: https://stackoverflow.com/a/7719185 — no jQuery required. (Note that there's a shorter Promise example a bit down in the answer; don't stop reading after the first example (like I did)).

And here for CSS: loadCSS: https://github.com/filamentgroup/loadCSS/blob/master/src/loadCSS.js

— this is, in a way, even better than YepNope.js, if you don't need any of its features except for just loading stuff + callback. Because the stuff linked above, is smaller (smaller min.js.gz) than yepnope.js.

(And can combine with Modernizr like mhk showed in his answer.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.