How to keep CSS from render-blocking my website?

前端 未结 2 1980
慢半拍i
慢半拍i 2021-02-20 16:29

I am trying to optimize the loading speed of my mobile webpage, and for that effect I am using the website:

  • https://developers.google.com/speed/pagespeed/insights<
2条回答
  •  故里飘歌
    2021-02-20 17:23

    You can do it with JavaScript:

    
    

    The font will be loaded out-of-band with the main rendering. Of course, that means there will be a visual change when the font finishes loading...and if the user has JavaScript disabled, it won't load the font at all.


    Or, as dandavis points out, you could just use a style element at the end of body, just before the closing tag:

    
    

    That's valid HTML now (as of the 20170808 draft of HTML 5.2), but I'd never met a browser that cared about it if you placed style in body even before it was made valid.

    The advantages to this over using JavaScript are:

    1. In theory, the browser's prefetch scanner might find the style element and start the download earlier (although this isn't particularly likely if you put the JavaScript in head), and

    2. It works even if the user has JavaScript disabled.

    Alternately, you could just move your link element to the end of body, but at present, that's invalid and the scoped attribute doesn't (yet?) seem to apply. (Why make it apply to style and not link[rel=stylesheet]? I have no idea, and perhaps it's simply a matter of not having got there yet...)

提交回复
热议问题