DEV Community

mahasun
mahasun

Posted on

Optimizing External Libraries with the defer Attribute: Boosting Page Speed

When building a website, developers often rely on external libraries to enhance functionality. While these libraries are essential, they can impact performance because each external script requires an additional HTTP request, and its parsing, evaluation, and execution can block the rendering of the main content on the page. To prevent these scripts from blocking the rendering process, developers can use the async or defer attributes when linking external scripts.

The Role of defer
The defer attribute ensures that a script is not executed until the HTML parsing is complete. This helps in speeding up the page's initial rendering. However, when using deferred external libraries, you might encounter cases where certain functionalities (e.g., initializing sliders, carousels, or animations) fail to run as expected. This happens because the code inside the deferred script is executed only after the HTML is fully parsed, but sometimes the necessary external libraries might not be available in time.

Understanding DOMContentLoaded and load Events
To ensure that your custom code relying on external libraries executes correctly, you need to carefully manage the timing of when your code runs. Two JavaScript events are particularly useful when dealing with deferred scripts

DOMContentLoaded: This event fires when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, or other external resources to load. It is useful when your code only depends on the DOM structure being ready.

document.addEventListener('DOMContentLoaded', function() { 
// Initialize your script once the DOM is fully parsed 

console.log("DOM is ready, but external resources might still be loading."); 
});
Enter fullscreen mode Exit fullscreen mode

load: The load event fires when the entire page, including all dependent resources such as stylesheets, images, and external scripts, has fully loaded. This event ensures that all necessary external resources are available before executing your code.

window.addEventListener('load', function() { 
// Execute code when the entire page and resources are loaded 

console.log("All resources including external scripts are fully loaded."); 
});
Enter fullscreen mode Exit fullscreen mode
<script defer src="https://example.com"></script>
<script defer src="https://example2.com"></script>
<script>
    // Wait for the entire page, including scripts, to load
    window.addEventListener('load', function() {
        // Initialize example2 library with predefined configuration after all resources are fully loaded
        example2(somePredefinedConfig).functionCall();
    });
</script>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)