Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 573
IMB Avatar asked Feb 07 '23 18:02

IMB


2 Answers

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

like image 74
Hector Barbossa Avatar answered Feb 09 '23 09:02

Hector Barbossa


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...
}
like image 34
Miloš Đakonović Avatar answered Feb 09 '23 07:02

Miloš Đakonović