DEV Community

Discussion on: CSS, JavaScript, and blocking web page parsing

Collapse
 
quantuumsnot profile image
quantuumsnot

In simple words we must defer the script(s) instead of async if we want them to be executed properly on already LOADED HTML content

Collapse
 
sandhilt profile image
Bruno Ochotorena

You can use async + DOMContentLoaded event.
TL;DR; DOMContentLoaded is event when all html is parsed and is safety manipulated.

So, script is async downloaded and execute waiting DOM is ready

Example:

<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Example</title>

    <script async src="./test.js" />
</head>
<body>
    <main>
        <section id="example"></section>
    </main>
    // ...
</body>
</html>
Enter fullscreen mode Exit fullscreen mode
/* test.js */
(() => {
    function run() {
        const example = document.getElementById("example");
        console.log({ example })
        // ...
    }
    window.addEventListener('DOMContentLoaded', run);
})();
Enter fullscreen mode Exit fullscreen mode

More info about event here: developer.mozilla.org/en-US/docs/W...