Modern Asynchronous CSS Loading
Posted By : Rajan Rawat | 06-Feb-2018
The First way of loading the CSS file in HTML webpage we know that using the link element like rel="stylesheet"
Example
<link rel="stylesheet" href="mystyle.css">
This way of CSS loading work's great, but when it comes to another side like downside it is synchronous. In a typical statement, we can say that it is a typical stylesheet. while the requests it stops rendering the other part of the page it downloads or parses the file. On the other, this thing may be good because it help's us to make browser render the webpage before it loads the class. But if we look at that other side all the CSS files which are critical enough that could delay the content. so to load the CSS with the less-critical rate or without blocking page we need to load it asynchronously
Loading CSS Async
previously there are so many ways to load the CSS in the browser asynchronously, but they are not good as expected.
now we use javascript it will create and it will insert CSS link in the DOM
here we are using the javascript create and insert link of css into DOM
// creating a stylesheet link
var myCSS = document.createElement( "link" );
myCSS.rel = "stylesheet";
myCSS.href = "mycssfile.css";
// In the legacy-friendly manner it will be inserted at the end
document.head.insertBefore( myCSS, document.head.childNodes[ document.head.childNodes.length - 1 ].nextSibling );
The method that we are using here that we are triggering an asynchronous CSS <link> element for the media attribute it set an invalid value. whenever the media query value will be false in that browser also download the CSS file and it will not wait for content is available or not before rendering the webpage.
Example
<link rel="stylesheet" href="mycssfile.css" media="none">
Conclusion
The example of the non-blocking technique is loading fonts. But we can use this feature for other purposes as well as we can use it for separating javascript so the enhanced CSS or styles from core CSS
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Rajan Rawat
Rajan is a UI Developer, having good knowledge of HTML, CSS and javascript. His hobbies are internet surfing and watching sports.