admin管理员组

文章数量:1402803

Google PageSpeed test is telling me to use async

E.g. change

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

To

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

Will modernizer still work just fine?

Google PageSpeed test is telling me to use async

E.g. change

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

To

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

Will modernizer still work just fine?

Share Improve this question asked Jun 15, 2016 at 21:05 IMBIMB 15.9k23 gold badges87 silver badges150 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

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

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...
}

本文标签: javascriptIs it okay to async modernizrStack Overflow