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> <script> document.addEventListener('DOMContentLoaded', () => { console.log('DOM fully loaded and parsed'); }); </script>
This would produce the following output to the browser console
:
// 'external script loaded' // 'DOM fully loaded and parsed'
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.