This is the official shorthand for doc ready (in jQuery):
// Shorthand for $( document ).ready()
$(function() {
// do something
});
In some cases, we add document on handlers. For example:
$(function () {
$(document)
.on('click', '.save-order-button', function (e) {
saveOrder(e);
})
.on('change', '.select-product-quantity', handleChangeProductQuantity)
})
But my question is this: given the $(document).on example above, how would you add logic to be called on doc ready?
I would do it this way:
$(function () {
$(document)
.on('click', '.save-order-button', function (e) {
saveOrder(e);
})
.on('change', '.select-product-quantity', handleChangeProductQuantity);
// do below on $(document).ready
if ($('#isNewCustomer').val() === 'true') {
$('.profile').hide();
$('.links').hide();
}
callSomeOtherFunction();
})
A coworker prefers this way:
$(function () {
$(document)
.on('click', '.save-order-button', function (e) {
saveOrder(e);
})
.on('change', '.select-product-quantity', handleChangeProductQuantity)
.ready(() => {
if ($('#isNewCustomer').val() === 'true') {
$('.profile').hide();
$('.links').hide();
}
callSomeOtherFunction();
});
})
Is either way ok?
Is my coworker's way fine?
Is doc ready being fired twice in my coworker's example?
If we did both, for example, some in .ready(() =>, my coworker's way, and also some my way, would doc ready be getting fired twice? Which would be fired first?
Thx in advance.
Both work as intended. But the jQuery authors write the following about using
.ready():So this favours your version of the code.
Yes, all callbacks on the ready event get called, also handlers that are attached after the DOM is ready, which is the case in the alternative code.
The jQuery documentation ensures this:
I would certainly go for your version of the code. The additional
.ready()call gives the impression that the author has doubts whether that code can be executed synchronously, but of course it can, because it is already ensured that the DOM is ready.Another way to look at it, is that the alternative code doesn't need the
$(function () { })wrapper around it, and then it makes more sense to have the.ready()handler.But the main objection remains:
.ready()is deprecated since jQuery 3.0