问题
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.
- Does this mean that by setting
defer
attribute I can easily execute my script when DOM is ready? - Is there some hidden stuff I may miss?
- How well is supported i.e. Opera, WebKit, Firefox, IE?
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.
回答1:
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.
回答2:
If you are amenable to using JQuery ( http://jquery.com/ ) then you can use:
$(document).ready(
function(){
//do something here, the DOM is ready!
}
);
For the full details visit http://api.jquery.com/ready/
The .ready function will load after the DOM is ready and I believe (though I could be mistaken) that the JQuery team have largely taken care of anything which you (or I) might miss.
While you can tackle this without the overhead of JQuery, in my (novice) experience, the headache isn't worth the hassle. Also, JQuery has a lot of other nifty tools too. :)
来源:https://stackoverflow.com/questions/14503666/deferred-scripts-and-dom