IMB
IMB

Reputation: 15889

Is it okay to async modernizr?

Google PageSpeed test is telling me to use async

E.g. change

<script src="//cdnjs.cloudflare.com/ajax/libs/modernizr/2.6.2/modernizr.min.js"></script>

To

<script async src="//cdnjs.cloudflare.com/ajax/libs/modernizr/2.6.2/modernizr.min.js"></script>

Will modernizer still work just fine?

Upvotes: 4

Views: 3322

Answers (2)

Miloš Đakonović
Miloš Đakonović

Reputation: 3871

Modernizr does not need to be placeed in <head>.

Modernizr will work ultimately fine whenever you include it.

If you make modernizr script async, or include it after some of significant page loading events (DOMContentLoaded, window.onload...)

  • application of specific css rules (feature, no-feature classes in document's head) will be delayed.
  • availibility of window.Modernizr will also be delayed, together with it's object properties (i.e. Modernizr.propery)

In short,

  • bad thing that may happen to your CSS if you use async loading of Modernizr is improper styles (the ones that depends on <html> classes) applied for some time
  • bad thing that may happen to your JS code is, if you use Modernizr global object, you may not use it directly as it may and may not be loaded - you will have to wait for it by some manner. So, no more:

 

if(Modernizr.cssanimations){
    // your feature-dependant code
}

but instead:

if(typeof Modernizr !== "undefined"){
//uitilize Modernizr global object here
} else {
// implement waiting for this object, let's say write short onModernizrLoad() function...
}

Upvotes: 3

Hector Barbossa
Hector Barbossa

Reputation: 5528

Modernizr needs to be placed in the <head> for two reasons:

  1. html5shiv needs to be there for oldIE.
  2. avoiding the FOUC when using modernizr-placed classes for feature-conditional styling

You can use an async attribute and/or place it at the bottom if neither of these matter to you.

Look at this issue posted in Modernizr

Upvotes: 5

Related Questions