I have a .js file with many functions all applied to one page. I'm trying to optimize my jQuery code to reduce the loading time.
Many of the functions are defined this way :
$(document).on( "change", ".fields-abc", function () { ... });
$(document).on( "change", ".fields-xyz", function () { ... });
Since these functions target fields located in the same div#myid, I could improve loading time by including #myid in the selector :
$(document).on( "change", "#myid .fields-abc", function () { ... });
$(document).on( "change", "#myid .fields-xyz", function () { ... });
But I suppose it would be even better if #myid was in a variable, then i target this variable in all the different functions?
If this is indeed better, how do I modify the syntax to target this variable ? Like this ?
var myidvariable = $("#myid");
$(document).find(myidvariable).on( "change", "#myid .fields-abc", function () { ... });
$(document).find(myidvariable).on( "change", "#myid .fields-xyz", function () { ... });
I suppose not...
CodePudding user response:
Always add event to closes static element. So if you do not replace #myid
programmatically, then target it and chain your calls.
$('#myid')
.on('change', '.fields-abc', function () {})
.on('change', '.fields-xyz', function () {})
Please note that if you have var parent = $('#myid')
and .fields-*
are also static, then you can pass element to look for element as second parameter to jQuery constructor
var parent = $('#myid');
$('.fields-abc', parent).change(function () {})
CodePudding user response:
I'm trying to optimize to reduce loading time
The slowest part of your code, with respect to loading times, is the initial selector
$(document)
The selector
parameter of the event will not impact loading times as it's just a string and won't be used to initialise the event.
So the best way to optimise your code is to reduce the occurrences of $(selector)
, in your case you can do either:
var doc = $(document);
doc.on("change", ".abc", ...);
doc.on("change", ".xyz", ...);
or make use of jquery's chaining:
$(document)
.on("change", ".abc", ...)
.on("change", ".xyz", ...);
(note the ;
only after the second .on()
)
As noted, you can use a "closer" element, but the same principle applies, rather than:
$("#id").on(..);
$("#id").on(..);
chain the DOM query
$("#id").on(..).on(..);