dojo.addOnLoad(Function fn)
Sooner or later, every Javascript programmer tries something like this:
if (dayOfWeek == "Sunday" ){
document. musicPrefs. other. value = "Afrobeat";
}
</script>
<form name= "musicPrefs">
<input type= "text" name= "other">
...
It doesn't work because the "other" control is not defined yet. You can move the code to the bottom of the page, but that removes the linear nature of HTML. If you're reading the code, you want to zero in on a control, and see the code that influences it close by.
dojo.addOnLoad(...) defers script execution until all the HTML is loaded. So this code:
document. musicPrefs. other. value= "Afrobeat";
}
dojo. addOnLoad (setAfrobeat );
conveniently replaces the one above. When the function is small, you may prefer to write it inline:
function (){
document. musicPrefs. other. value= "Afrobeat";
}
);
This is the function literal or anonymous function construct of JavaScript. If it looks really, really wierd to you, take a peek ahead at Functions as Variables for an explanation.
本文探讨了使用Dojo框架中的addOnLoad方法解决JavaScript代码执行时机问题。通过将脚本执行延迟到DOM完全加载之后,实现了代码与HTML元素的同步加载,有效提升了用户体验。

被折叠的 条评论
为什么被折叠?



