Are Deferred Scripts Executed Before "DOMContentLoaded" Event?

Find out when the deferred external JavaScripts are executed

HTML <script> tags with the defer attribute are executed before the DOMContentLoaded event. To demonstrate this, consider the following external JavaScript:

// foo.js
console.log('external script loaded');

When you load this external script in your HTML page with the defer attribute, it will load just before the DOMContentLoaded event is fired. For example, consider the following code in the HTML page:

<!-- index.html -->
<script src="foo.js" defer></script>

document.addEventListener('DOMContentLoaded', () => {
    console.log('DOM fully loaded and parsed');

This would produce the following output to the browser console:

// 'external script loaded'
// 'DOM fully loaded and parsed'

Hope you found this post useful. It was published . Please show your love and support by sharing this post.