I need to run script only when DOM is ready as script does some rewriting of certain attributes of certain tags.
Currently I use document.addEventListener
on DOMContentLoaded
or if not available document.attachEvent
on onreadystatechange
and if both not given I use window.onload
functionality.
I read about defer
tag for scripts that should be executed after document is parsed.
defer
attribute I can easily execute my script when DOM is ready?Edit: I'm aware of libraries like JQuery but I can't use them as I need very small script so I need a low level solution.
A proper implementation of the defer
attribute will automatically run the script after the DOM has finished parsing so any code in the script does not have to do it's own logic for when the DOM is loaded. You can read this Mozilla article for more details.
However, the defer
attribute is not supported in all older browsers so you have to decide what browsers you want to support and what your strategy is for any that don't support defer. You can read the history of browser implementation in this SO post. In a switcheroo, it was implemented first in IE, then in Firefox, then in Safari and Chrome. Judging by the dates/versions in that post, it looks like it's pretty safe to rely on it now except for Opera, but you'll have to dive into the details in that post to be sure it meets your requirements.
Here's a chart that shows browser support for defer
: http://caniuse.com/script-defer.
As best I can tell, the main controversy with defer
is whether multiple defer
scripts execute in order or not (they are supposed to execute in order) and how they interact with scripts that use async
. The standards and implementations are now clear, but were not always. But, if you just have one stand-alone defer
script that you only care about executing after the DOM is parsed, you should be safe.