Increase page speed in one step: use css async loading

Asynchronous CSS loading on the site

4 Shares
4
0
0

Asynchronous CSS loading allows you to speed up the loading of website pages. This is very important for mobile devices when internet connections can be slow.

Loading with jQuery

If you use jQuery, you can load the css asynchronously this way:

$("head").append("<link rel='stylesheet' type='text/css' href='/styles.css' />");

This code should be executed after loading the document and jQuery respectively, for example in the ready method:

$(document).ready(function() {
    $("head").append("<link rel='stylesheet' type='text/css' href='/styles.css' />");
})

In this case, all HTML will be loaded without blocking (waiting for CSS to load). Because CSS will be loaded after the HTML, the visitor will see the site without styles until they are loaded. In order to keep the appearance of the site, you need to add a style tag with all the styles needed to display the top of the page. All code will look like this:

<html>
<head>
<style>
h1 { color: #444 }
</style>
</head>
<body>
<h1>Заголовок</h1>
<hr/>
...
<script src="/jquery.js"></script>
<script>
    $(document).ready(function() {
        $("head").append("<link rel='stylesheet' type='text/css' href='/styles.css' />");
    });
</script>
</body>
</html>

In the tag style you need to set the minimum number of styles needed to load the first screen.

4 Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like