Introduction:
Looking to give your website a speed boost? We’ve got you covered with an easy trick: lazy loading FontAwesome icons using JavaScript. In this guide, we’ll walk you through the process step by step, making your site load faster and keeping your visitors happy.
Why It Matters:
- Let’s talk about why loading FontAwesome icons can slow down your website.
- Discover how lazy loading saves the day by only loading icons when they’re needed.
How to Do It:
- We’ll introduce you to the handy “loadCSS” JavaScript function made for lazy loading FontAwesome.
- Don’t worry, we’ll break down the code into plain English so you can understand how it works.
<script>
/* code by atcodez*/
function loadCSS(e, t, n) { “use strict”; var i = window.document.createElement(“link”); var o = t || window.document.getElementsByTagName(“script”)[0]; i.rel = “stylesheet”; i.href = e; i.media = “only x”; o.parentNode.insertBefore(i, o); setTimeout(function () { i.media = n || “all” }) }loadCSS(“https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.3.0/css/all.min.css”);
</script>
Here’s a breakdown of how the code works:
- We define a function called “loadCSS” that takes three arguments: the URL of the CSS file, the element to insert the link before (optional), and the media type (optional).
- We create a new link element using the “createElement” method and set its “rel” attribute to “stylesheet.”
- We set the “href” attribute of the link to the URL of the Font Awesome CSS file.
- We set the “media” attribute of the link to “only x,” which means that the browser will only download the CSS file when it’s necessary.
- We insert the link element into the document’s head using the “insertBefore” method.
- We use the “setTimeout” method to set the “media” attribute of the link to “all” after a certain amount of time. This ensures that the Font Awesome icons will be visible on the page when they’re needed.
Conclusion:
And that’s it! By lazy loading the Font Awesome library, you can improve your website’s loading time and provide a better user experience for your visitors.