No - with defer, the script will wait for the browser to finish parsing the HTML into a DOM tree, but will not wait for all of the page's assets (like images, css, 3rd-party files, etc.) to finish loading. Often you don't need to wait quite so long as the load event before your JS can start doing things like DOM manipulation (hiding an element, etc.), adding event listeners, etc., you just need the DOM to be set up. But if you do need to wait for load, you can use defer on the script tag but you still need to wrap your code in a window.addEventListener('load') event.
Great article. Does defer remove the need to use the document load / onload event to only run some code when the doc is fully loaded?
No - with
defer
, the script will wait for the browser to finish parsing the HTML into a DOM tree, but will not wait for all of the page's assets (like images, css, 3rd-party files, etc.) to finish loading. Often you don't need to wait quite so long as theload
event before your JS can start doing things like DOM manipulation (hiding an element, etc.), adding event listeners, etc., you just need the DOM to be set up. But if you do need to wait forload
, you can usedefer
on thescript
tag but you still need to wrap your code in awindow.addEventListener('load')
event.That makes sense. Thank you!