Skip to content

Laggy when applied to multiple elements #617

@iamdriz

Description

@iamdriz

I was using Waypoints and Inview to add animations to several elements on a website when they became in view...

function setAnimations() {
    $('.animation').each(function () {
        new Waypoint.Inview({
            element: $(this),
            enter: function () {
                if(!$(this.element).hasClass('animation--completed'))
                    $(this.element).addClass('animation--animated');
            }
        });
        $(this).one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function () {
            $(this).removeClass('animation--animated').addClass('animation--completed');
        });
    });
}

However I found severe lag happening during the code adding the Waypoint instance to each element... and was able to actually write a jQuery function that does exactly the same thing I wanted and it runs with no lag at all...

$.fn.visible = function () {
    let $this = $(this),
        $window = $(window),
        top = $window.scrollTop(),
        bottom = top + $window.height(),
        offsetTop = $this.offset().top,
        offsetBottom = offsetTop + $this.height(),
    return ((offsetTop <= bottom) && (offsetBottom >= top));
};

function setAnimations() {
    function animations() {
        $('.animation').each(function (i, el) {
            if ($(el).visible(true)) {
                if (!$(el).hasClass('animation--completed'))
                    $(el).addClass('animation--animated');
            }
            $(el).one('webkitAnimationEnd animationend', function () {
                $(this).removeClass('animation--animated').addClass('animation--completed');
            });
        });
    }
    $(window).scroll(function () {
        animations();
    });
    $(window).resize(function () {
        animations();
    });
    animations();
}

Any ideas why Waypoints creates such substantial lag in comparison to what I used instead? I understand Waypoints adds additional functionality... but the lag was causing delays on the page load of over 3-4 seconds...

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions