Reputation: 85
Okay so how can I use loadCSS (https://github.com/filamentgroup/loadCSS/blob/master/README.md) to allow the browser to asynchronously load CSS and JavaScript?
I have this in my head tag:
<link rel="preload" href="http://zoidstudios.com/assets/css/main.css" as="style" onload="this.rel='stylesheet">
<noscript><link rel="stylesheet" href="http://zoidstudios.com/assets/css/main.css"></noscript>
And this at the bottom of my html file :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://use.fontawesome.com/eb515f50a5.js"></script>
<script src="http://zoidstudios.com/assets/js/functions.min.js"></script>
<script src="http://zoidstudios.com/assets/js/loadcss.min.js"></script>
<script>
loadCSS( "http://zoidstudios.com/assets/css/main.css" );
</script>
Upvotes: 3
Views: 4204
Reputation: 2550
The problem is not with the CSS. If PageSpeed thinks your page load is bogged down, it's probably the result of all those <script>
tags at the end of your <body>
tag. Just because they are placed in the body tag does not mean they are asynchronous.
You can leave them all in the <head>
tag. You can include the attribute async
or defer
to get asynchronous loading: have a look at this explanation.
So, something like this should do:
<script
src="http://zoidstudios.com/assets/js/functions.min.js"
defer>
</script>
Note that if any of those scripts expect the DOM to be parsed (i.e., they expect certain elements to exist already), you should use defer
instead of async
, as explained in the linked article. Or, you can leave those in the <body>
tag, and use async
.
If my hypothesis is correct (that PageSpeed does not support rel='preload'
on <link>
tags), notice that the documentation linked in your question advises you to
include the loadCSS script, as well as the loadCSS rel=preload polyfill script in your page (inline to run right away, or in an external file if the CSS is low-priority)
You may be able to eliminate the final warning by using the recommended polyfill.
The general problem, "how do I load CSS asynchronously?" has been asked and answered many times on StackOverflow, as I'm sure you know!
Upvotes: 0
Reputation: 1716
Have you looked into loaders like RequireJS or webpack? Most loaders will support CSS natively and/or offer CSS plugins to load CSS, JS, etc. asynchronously all while ensuring dependencies. If you have many files to load I would suggest looking into a loader of your preference.
Upvotes: 1