It seems like all the key points were already hit, but a few details fell through the cracks. Mainly:
domReady
It is both a plugin and a module. If you include it in the the requirements array w/ a trailing !
your module won't execute until it's "safe" to interact w/ the DOM:
define(['domReady!'], function () {
console.info('The DOM is ready before I happen');
});
Note that loading and executing are different; you want all your files to load as soon as possible, it's the execution of the contents that is time sensitive.
If you omit the !
, then it's just a normal module that happens to be a function, which can take a callback that won't execute before the DOM is safe to interact with:
define(['domReady'], function (domReady) {
domReady(function () {
console.info('The DOM is ready before I happen');
});
console.info('The DOM might not be ready before I happen');
});
Advantage when using domReady as a plugin
Code that depends on a module that in turn depends on domReady!
has a very significant advantage: It does not need to wait for the DOM to be ready!
Say that we have a block of code, A, that depends on a module, B, that depends on domReady!
. Module B will not finish loading before the DOM is ready. In turn, A will not run before B has loaded.
If you were to use domReady
as a regular module in B, it would also be necessary for A to depend on domReady
, as well as wrapping its code inside a domReady()
function call.
Furthermore, this means that domReady!
enjoys that same advantage over $(document).ready()
.
Re the differences between domReady and $(document).ready()
Both sniff out whether/when the DOM is ready in essentially the same way.
Re fear of jQuery firing at the wrong time
jQuery will fire any ready callback even if the DOM loads before jQuery does (your code shouldn't care which happens first.).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…