简体   繁体   中英

JS - Most efficient way of running functions

This might be off-topic, so forgive me if it is. I'm trying to optimize a site I'm working on which is quite JS / jQuery heavy.

This is how I'm triggering functions right now;

<a class="js-trigger" data-trigger-type="modal">Trigger a modal</a>
<a class="js-trigger" data-trigger-type="animation">Trigger an animation</a>
$('.js-trigger').on('click', function() {
    var triggerType = $(this).data('trigger-type');
    if ( triggerType === 'modal' ) {
        sampleModalFunction();
    }
    else if ( triggerType === 'animation' ) {
        sampleAnimationFunction();
    }
});

It seems to be more efficient than running multiple .on('click') functions, but am I really causing more load time than I'm trying to save?

<a class="js-trigger" data-trigger-type="modal">Trigger a modal</a>
<a class="js-trigger" data-trigger-type="animation">Trigger an animation</a>


        $('.js-trigger').on('click', function() {
            if ( $(this).data('trigger-type') === 'modal' ) {
                sampleModalFunction();
            }
            else {
                sampleAnimationFunction();
            }
        });

Try not using extra variables also and else If conditions.

thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM