Lazy Loading CSS and JS file to improve Your web page speed


In this article, we will discuss how to lazy loading CSS and Javascript files to improve web page speed by, including important considerations.

We will adopt a method which the files targeted for lazy loading are loaded when the user scrolls.





Advantages of Lazy Loading

While visitors to this article may already be familiar with the concept, it’s worth briefly mentioning the benefits of lazy loading CSS and JS files. The primary advantage can be summed up as a significant enhancement in page loading speed.

By delaying the loading of styles and scripts that are not necessary for the initial display, page loading speed can be significantly improved. The heavier the delayed styles and scripts are, the more dramatic the improvement in loading speed can be.


We will adopt a method which the files targeted for lazy loading are loaded when the user scrolls but not at the initial display.






Code for Lazy Loading (Beginner-Level)

Create a function to dynamically load CSS and JS files

First, prepare a function to dynamically load CSS or JS files. This function takes the URL of the file as an argument and generates a <link> or <script> tags, then appends them to the body.
In this example, the file is named load-file.js.

function loadCss(url) {
    const link = document.createElement('link')
    link.rel='stylesheet'
    link.href = url
    document.body.appendChild(link)
}

function loadJs(url) {
    const script = document.createElement('script')
    script.src = url
    document.body.appendChild(script)
}


Code to Execute Lazy Loading

At the moment when the user performs scrolling, the previously defined loadCss and loadJs functions are called to execute the lazy loading of CSS and JS files.
We are using the once option to execute the event only once.

<script src="./js/load-file.js"></script>
<script>
    window.addEventListener('scroll', function() {
        loadCss('./css/style.css')
        loadCss('./css/common.css')
        loadJs('./js/function.js') 
        loadJs('./js/common.js') 
    },{once:true})
</script>






Two Considerations for Lazy Loading of CSS and JS Files

Point 1: Do not lazy loading files that are essential for the first view

The method explained above involves “loading CSS and JS files when scrolled.” Therefore, if you lazy loading files essential for the first view, the display which user see might become distorted.

Choose only those files for lazy loading that are not crucial for the first view.

Pay attention to event handlers in the JavaScript file being lazy loaded

For instance, if the lazily loaded JavaScript contains events like the one below, the content within that event will not be executed.
The DOMContentLoaded event is executed when the DOM construction is completed. However, when files are lazily loaded, the DOM construction has already been completed by the time the files are loaded.

document.addEventListener('DOMContentLoaded', function() {

})


In my understanding, the following four types of code do not work with lazy loading. These can be categorized into two event types: the DOMContentLoaded event and the load event.

document.addEventListener('DOMContentLoaded', function(){  })

window.addEventListener('load', function(){ })

window.onload = function(){ }

$(window).on('load', function(){ })


However, this can be resolved by triggering a forced execution using dispatchEvent during the lazy loading process, as shown below.

window.addEventListener('scroll', function() {
    loadCss('./css/style.css')
    loadCss('./css/common.css')
    loadJs('./js/function.js') 
    loadJs('./js/common.js') 

    /*      ↓ 追記 ↓      */
    setTimeout(function(){ 
        window.dispatchEvent(new Event('load'))
        document.dispatchEvent(new Event('DOMContentLoaded')) 
    },500)
},{once:true})






About the Complete Code for the Beginner-Level

Below is the complete code for the beginner-level implementation.

window.addEventListener('scroll', function() {
    loadCss('./css/style.css')
    loadCss('./css/common.css')
    loadJs('./js/function.js') 
    loadJs('./js/common.js') 
    setTimeout(function(){ 
        window.dispatchEvent(new Event('load'))
        document.dispatchEvent(new Event('DOMContentLoaded')) 
    },500)
},{once:true})

function loadCss(url) {
    const link = document.createElement('link')
    link.rel='stylesheet'
    link.href = url
    document.body.appendChild(link)
}

function loadJs(url) {
    const script = document.createElement('script')
    script.src = url
    document.body.appendChild(script)
}






Up to this point, the explanation about how to lazy loading CSS and JS file including important considerations has concluded. Moving forward to the advanced level, there won’t be any changes to the features provided to users. We will not achieve more than the enhancement of loading speed through lazy loading.


From here on, we will simply refactor the beginner-level code to make it more conducive for writing source code.
We will accomplish the following two tasks:

・Move the lazy loading process into functions to enhance reusability.
・Enable managing the URLs of files to be lazily loaded through a configuration file.



Please proceed if you’re interested.




Code for Lazy Loading (Advanced-Level)

We will prepare a set of functions like the following.
These function accepts an object of arrays containing URLs of CSS and JS files, as well as arrays for force-firing events, as arguments. When the user scrolls, these functions will handle both lazy loading and force-firing events.

In this example, the file is named lazy-file.js.

function lazyFile({css=[], js=[], events=[]}, lazyloaded=false) {
    window.addEventListener('scroll', () => {
        css.map((url) => loadCss(url))
        js.map((url) => loadJs(url))
        fireEvents(events) 
    },{once:true})
}

function fireEvents(events) {
    setTimeout(() => { 
        events.map((event) => {
            window.dispatchEvent(new Event(event))
            document.dispatchEvent(new Event(event))  
        })
    },500)
}

function loadCss(url) {
    const link = document.createElement('link')
    link.rel = 'stylesheet'
    link.href = url
    document.body.appendChild(link)
}

function loadJs(url) {
    const script = document.createElement('script')
    script.src = url
    document.body.appendChild(script)
}


You can perform lazy loading using the lazyFile function prepared earlier.

<script src="./js/lazy-file.js"></script>
<script>
    lazyFile({
        css: [
            './css/style.css',
            './css/common.css',
        ],
        js: [
            './js/function.js',
            './js/common.js',
        ],
        events: [
            'load',
            'DOMContentLoaded',
        ]
    })
</script>



By organizing the file URLs and desired force-firing events in array format, this part can now be managed as configuration values in an external file.

For instance, if you prepare a configuration file like the following …

const Const = {
    LAZY_CSS: [
        './css/style.css',
        './css/common.css',
    ],
    LAZY_JS: [
        './js/function.js',
        './js/common.js',
    ],
    LAZY_EVENTS: [
        'load',
        'DOMContentLoaded',
    ]
}



You can now perform lazy loading as shown below.
The procedural code has become much cleaner.

<script src="./js/lazy-file.js"></script>
<script src="./js/const.js"></script>
<script>
    lazyFile({
        css: Const.LAZY_CSS,
        js: Const.LAZY_JS,
        events: Const.LAZY_EVENTS
    })
</script>







That is all, it was about Lazy Loading CSS and Javascript file!

Sponsored Link

You can subscribe by SNS

Sponcerd Link

Leave a Reply

*