Recently I've been working on a relatively simple personal project where I need to generate quite a fair amount of Javascript to bind various event handlers to elements (such as on('click')
) and it got me wondering about the efficiency of generating multiple on('click')
definitions per element, based on the values in the array (which could change per page load), or having a single function that binds it to every element. For example:
PHP generating jQuery
<?php
foreach($var as $key => $val){
echo '$("' . $key . '").on("click", function(){
// do something
});';
}
// Which will generate:
// $(elemkey1).on("click", function(){ // do something });
// $(elemkey2).on("click", function(){ // do something });
// $(elemkey3).on("click", function(){ // do something });
// $(elemkey4).on("click", function(){ // do something });
// ...
Pure jQuery
$(elem).each(function(){
// do something
);
So my question is: Which would be the most efficient way of declaring something like the above?
Obviously the second example is dependant on the selector used (whether it's an id
or class
for example and I'm fully aware of the caveats here) but that aside, assuming the right selectors are used, I'm curious to know if there's a slight performance benefit in declaring event handlers per element explicitly using a PHP for loop as opposed to the jQuery .each()
or similar method.