I'm trying to eliminate 2 CSS files that are render blocking on my site - they appear on Google Page Speed Insights. I have followed different methods, none of which were a success. But, recently, I found a post about Thinking Async and when I applied this code: <script async src="https://third-party.com/resource.js"></script>
it did eliminate the problem.
However, after publishing, the page lost the styling. I'm not too sure as to what is going on because the code works but it's the styling after upload that doesn't work. Would appreciate your help with this. Thanks
Please care to update the answer as all of the above fails to impress google pagespeed insights now.
According to Google this is how you should implement async loading of Css
The trick to triggering an asynchronous stylesheet download is to use a
<link>
element and set an invalid value for the media attribute (I'm using media="none", but any value will do). When a media query evaluates to false, the browser will still download the stylesheet, but it won't wait for the content to be available before rendering the page.Once the stylesheet has finished downloading the media attribute must be set to a valid value so the style rules will be applied to the document. The onload event is used to switch the media property to all:
This method of loading CSS will deliver useable content to visitors much quicker than the standard approach. Critical CSS can still be served with the usual blocking approach (or you can inline it for ultimate performance) and non-critical styles can be progressively downloaded and applied later in the parsing / rendering process.
This technique uses JavaScript, but you can cater for non-JavaScript browsers by wrapping the equivalent blocking
<link>
elements in a<noscript>
element:You can see the operation in www.itcha.edu.sv
Source in http://keithclark.co.uk/
The function below will create and add to the document all the stylesheets that you wish to load asynchronously. (But, thanks to the
Event Listener
, it will only do so after all the window's other resources have loaded.)See the following:
Preload
You can now use the
preload
keyword forlink
elements.Sync version:
Async version:
Note
This feature just recently became widely supported among modern browsers. If you require fallbacks for older browsers, use loadCSS.
Update (07/18)
This feature has been disabled by default in Firefox. Until Firefox implements a solution, loadCSS (mentioned above) is likely your best bet. Comment below taken from this discussion:
you can try to get it in a lot of ways :
1.Using
media="bogus"
and a<link>
at the foot2.Inserting DOM in the old way
3.if you can try plugins you could try loadCSS
If you have a strict content security policy that doesn't allow @vladimir-salguero's answer, you can use this (please make note of the script
nonce
):Just add the following to your stylesheet reference:
media="none" data-async="true"
. Here's an example:Example for jQuery: