Jump to content
Search Community

Recommended Posts

Posted

 

I am new to frontend and have started using gsap for animations. I use gsap mainly for switching between sections. On screens larger than 576px I have a problem: when switching between sections there are jumps and they disappear after a while if you scroll up and down the page. Maybe someone has encountered this ?
I don't seem to have a lot of animations so far, but already so laggy. 

Here's what I tried to do:
1. Remove all possible negative margins.
2. Add to all elements to which the transition is made, properties: 
transform: translate3d(0,0,0,);
    will-change: transform;
    backface-visibility: hidden;
3. Set property ease - sine, power1, power2.

All this had no effect.

In the mobile version I have a lot of animation that works perfectly with gsap. 

 

See the Pen MYWvPvJ by bcnngjlt-the-scripter (@bcnngjlt-the-scripter) on CodePen.

Posted

Hi @Yakiv and welcome to the GSAP Forums!

 

Unfortunately your codepen has far too much code and we don't have the time resources to comb through all that HTML/CSS/JS trying to find what could be the issue(s) in your code, is beyond the scope of what we do in these free forums. We need a minimal demo (emphasis on minimal) just a few colored divs that clearly reproduce and illustrates the issues you're having.

 

One option in your current demo could be to disable some parts of your code until things start working the way you intend, then you'll know exactly what part of your code is causing the problems.

Posted
13 hours ago, Rodrigo said:

Hi @Yakiv and welcome to the GSAP Forums!

 

Unfortunately your codepen has far too much code and we don't have the time resources to comb through all that HTML/CSS/JS trying to find what could be the issue(s) in your code, is beyond the scope of what we do in these free forums. We need a minimal demo (emphasis on minimal) just a few colored divs that clearly reproduce and illustrates the issues you're having.

 

One option in your current demo could be to disable some parts of your code until things start working the way you intend, then you'll know exactly what part of your code is causing the problems.

I've noticed that by removing <div class=“zones-bg”></div> the lags and jumps on large screens disappear. On normal laptops everything is displayed normally.
Here is the html, css and js regarding scrolling and backgroud animation:

 

<section class="zones">
            <div class="zones-bg"></div>
            <div class="container">
                <article class="pool-spa">
                    <div class="inside-wrap-article">
                        <h3 class="animated-element"><span class="text-blue">Твої</span> басейни та спа зона на вершині
                            міста</h3>
                        <picture>
                            <source srcset="{{ url_for('static', filename='img/pool-spa-full.webp') }}"
                                media="{{ min_width_576 }}">
                            <img src="{{ url_for('static', filename='img/mob/pool-spa.webp') }}" alt="Spa and poll"
                                class="main-img animated-element">
                        </picture>
                        <picture>
                            <source srcset="{{ url_for('static', filename='img/pattern-left-s-1-full.png') }}"
                                media="{{ min_width_576 }}">
                            <img src="{{ url_for('static', filename='img/mob/pattern-left-s-1.png') }}" alt="Pattern"
                                class="pattern-s pattern-left">
                        </picture>
                        <picture>
                            <source srcset="{{ url_for('static', filename='img/pattern-right-3-full.png') }}"
                                media="{{ min_width_576 }}">
                            <img src="{{ url_for('static', filename='img/mob/pattern-right-3.png') }}" alt="Pattern"
                                class="pattern-l pattern-right animated-element">
                        </picture>
                    </div>
                </article>
                <article class="fitness-roof">
                    <div class="inside-wrap-article">
                        <h3 class="animated-element"><span class="text-yellow">Твій</span> фітнес на краю неба</h3>
                        <picture>
                            <source srcset="{{ url_for('static', filename='img/fitness-roof-full.webp') }}"
                                media="{{ min_width_576 }}">
                            <img src="{{ url_for('static', filename='img/mob/fitness-roof.webp') }}" alt="Fitness roof"
                                class="main-img animated-element">
                        </picture>
                        <picture>
                            <source srcset="{{ url_for('static', filename='img/pattern-left-3-full.png') }}"
                                media="{{ min_width_576 }}">
                            <img src="{{ url_for('static', filename='img/mob/pattern-left-3.png') }}" alt="Pattern"
                                class="pattern-l pattern-left">
                        </picture>
                        <picture>
                            <source srcset="{{ url_for('static', filename='img/pattern-right-s-1-full.png') }}"
                                media="{{ min_width_576 }}">
                            <img src="{{ url_for('static', filename='img/mob/pattern-right-s-1.png') }}" alt="Pattern"
                                class="pattern-s pattern-right">
                        </picture>
                    </div>
                </article>
            </div>
        </section>
.zones {
    overflow: hidden;
    position: relative;
    margin-top: 5rem;
    margin-bottom: -3rem;
    z-index: 0;
  }
 
  .zones .zones-bg {
    display: inline-block;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: calc(100vw* 1.2);
    background-image: url('../img/img-3-full.webp');
    background-repeat: no-repeat;
    background-size: cover;
    will-change: transform;
  }
 
/* Parallax for bg of zones */
      gsap.to(".zones .zones-bg", {
        y: "90vw", // Параллакс-эффект
        ease: "none",
        scrollTrigger: {
          trigger: ".zones",
          start: "top top",
          end: "bottom bottom",
          scrub: true,
        },
      });
 
      function scrollToSectionPC(index) {
        if (isScrolling || index < 0 || index >= sections_pc.length) return;
 
        let duration_main = 1.8; // Duration of animation of transitions between sections
 
        if (
          (currentIndex === 1 && index === 0) ||
          (currentIndex === 0 && index === 1)
        ) {
          duration_main = 2.2;
        }
 
        isScrolling = true;
        let targetSection = sections_pc[index];
        let offset = 0; // По умолчанию смещение составляет 30px от верха секции
 
        const height_section = sections_pc[index].offsetHeight / 2;
        let offset_center = window.innerHeight / 2 - height_section;
        // set offset for different section or execution prevent action before change section
        switch (index) {
          case 1: // For section (.block-desc) the center of the screen
            offset = offset_center + height_section;
            break;
          case 2: // .zones .pool-spa the center of the screen
            offset = offset_center;
            break;
          case 3: // .zones .fitness-roof the center of the screen
            offset = offset_center;
            break;
          case 4: // .zones .bbq-roof the center of the screen
            offset = offset_center;
            break;
          case 5: // .zones .sunset the center of the screen
            offset = offset_center;
            break;
          case 6: // .zones .school the center of the screen
            offset = offset_center;
            break;
        }
 
        // change section
        gsap.to(window, {
          duration: duration_main,
          scrollTo: { y: targetSection, offsetY: offset },
          ease: "power1.inOut",
          onStart: () => updateClassesPC(index),
          onComplete: () => {
            isScrolling = false;
            currentIndex = index;
          },
        });
      }

As soon as I return the <div class=“zones-bg”></div> element, everything starts lagging again. 
The resolution of the image used is 2560 x 3072 pixels and the size is 272kb. The sizes of the other images for the background are: 2560 x 3658 and 2560 x 1534 pixels. All of them are set via css as backgroud. 
Why does this cause such problems and how to optimize it?

GSAP Helper
Posted

Without a minimal demo, it's very difficult to troubleshoot; the issue could be caused by CSS, markup, a third party library, a 3rd party script, etc. Would you please provide a very simple CodePen or Stackblitz that illustrates the issue? 

 

Please don't include your whole project. Just some colored <div> elements and the GSAP code is best. See if you can recreate the issue with as few dependencies as possible. Start minimal and then incrementally add code bit by bit until it breaks. Usually people solve their own issues during this process! If not, at least we have a reduced test case which greatly increases your chances of getting a relevant answer.

 

See the Pen aYYOdN by GreenSock (@GreenSock) on CodePen.

that loads all the plugins. Just click "fork" at the bottom right and make your minimal demo

 

Using a framework/library like React, Vue, Next, etc.? 

CodePen isn't always ideal for these tools, so here are some Stackblitz starter templates that you can fork and import the gsap-trial NPM package for using any of the bonus plugins: 

 

Please share the StackBlitz link directly to the file in question (where you've put the GSAP code) so we don't need to hunt through all the files. 

 

Once we see an isolated demo, we'll do our best to jump in and help with your GSAP-specific questions. 

Posted
1 hour ago, GSAP Helper said:

Без  минимальной устойчивости очень сложно устранить неполадки; проблема может быть вызвана CSS, разметкой, внешней библиотекой, строкой скриптом и т. д. д. д. Не могли бы вы ответить на очень простой пример CodePen или Stackblitz, иллюстрирующий проблему? 

 

Пожалуйста, не включайте весь свой проект.  Только несколько цветных <div>элементов и лучше всего код GSAP. Решение проблемы с учетом обстоятельств зависит. Начните с минимума, а затем постепенно добавляйте код по частям, пока он не сломается. Обычно люди сами решают свои проблемы в ходе этого процесса! Если нет, то в меньшей степени у нас есть уменьшенный тестовый случай, который значительно увеличивает вероятность получения правильного ответа.

 

 

который загружает все плагины. Просто нажмите «вилку» внизу справа и сделайте свою минимальную демо-версию

 

 

Используйте свои библиотеки/фреймворки вроде React, Vue, Next и т. д. д. д.? 

CodePen не всегда идеально подходит для этих инструментов, поэтому вот несколько стартовых шаблонов Stackblitz , которые вы можете разветвить и импортировать пакет NPM gsap-trial  для использования любых из бонусных плагинов: 

 

Пожалуйста, воспользуйтесь ссылкой StackBlitz непосредственно над нужным файлом (куда вы поместили код GSAP), чтобы мы не могли просматривать все файлы. 

 

Как только мы увидим проведение проверок, мы сделаем все возможное, чтобы подключиться и помочь вам с вопросами, касающимися GSAP. 

I tried to recreate a minimal demonstration of the project.
The jumps and lags when switching to different sections remain.

See the Pen MYWvPvJ by bcnngjlt-the-scripter (@bcnngjlt-the-scripter) on CodePen.

Posted

I've already resized all the large images for the background and it still lags and jumps when scrolling. 
Can someone please help me?

Posted

Hi,

 

I tested your demo and I can see some flickering in Firefox on Ubuntu (not a lot on OSX though), it works fine on chrome (ubuntu 22 and OSX) but it doesn't look really good on safari though.

 

A lot of performance problems are down to how browsers and graphics rendering work. It's very difficult to troubleshoot blind and performance is a DEEP topic, but here are some tips: 

  1. Try setting will-change: transform on the CSS of your moving elements. 
  2. Make sure you're animating transforms (like x, y) instead of layout-affecting properties like top/left. 
  3. Definitely avoid using CSS filters or things like blend modes. Those are crazy expensive for browsers to render.
  4. Be very careful about using loading="lazy" on images because it forces the browser to load, process, rasterize and render images WHILE you're scrolling which is not good for performance. 
  5. Make sure you're not doing things on scroll that'd actually change/animate the size of the page itself (like animating the height property of an element in the document flow)
  6. Minimize the area of change. Imagine drawing a rectangle around the total area that pixels change on each tick - the bigger that rectangle, the harder it is on the browser to render. Again, this has nothing to do with GSAP - it's purely about graphics rendering in the browser. So be strategic about how you build your animations and try to keep the areas of change as small as you can.
  7. If you're animating individual parts of SVG graphics, that can be expensive for the browser to render. SVGs have to fabricate every pixel dynamically using math. If it's a static SVG that you're just moving around (the whole thing), that's fine - the browser can rasterize it and just shove those pixels around...but if the guts of an SVG is changing, that's a very different story. 
  8. data-lag is a rather expensive effect, FYI. Of course we optimize it as much as possible but the very nature of it is highly dynamic and requires a certain amount of processing to handle correctly.
  9. I'd recommend strategically disabling certain effects/animations and then reload it on your laptop and just see what difference it makes (if any). 

Ultimately there's no silver bullet, like "enable this one property and magically make a super complex, graphics-heavy site run perfectly smoothly even on 8 year old phones" 

 

Finally you might want to check the Observer Plugin since it seems a better alternative for what you're trying to achieve here:

See the Pen XWzRraJ by GreenSock (@GreenSock) on CodePen.

 

Hopefully this helps

Happy Tweening!

Posted
35 minutes ago, Rodrigo said:

Привет,

 

Я протестировал вашу демо-версию и заметил некоторое мерцание в Firefox на Ubuntu (хотя на OSX его не так много), в Chrome (Ubuntu 22 и OSX) все работает отлично, но в Safari выглядит не очень хорошо.

 

Многие проблемы с производительностью связаны с тем, как работают браузеры и рендеринг графики. Очень сложно устранять неполадки вслепую, а производительность — это ГЛУБОКАЯ тема, но вот несколько советов: 

  1. Попробуйте настроить CSS для ваших движущихся элементов.   will-change: transform 
  2. Убедитесь, что вы анимируете преобразования (например, x, y), а не свойства, влияющие на макет, например, верх/лево. 
  3. Определенно избегайте использования фильтров CSS или вещей вроде режимов смешивания. Они безумно дороги для браузеров для рендеринга.
  4. Будьте очень осторожны при использовании параметра loading="lazy" для изображений, поскольку он заставляет браузер загружать, обрабатывать, растеризовать и отображать изображения ВО ВРЕМЯ прокрутки, что не очень хорошо сказывается на производительности. 
  5. Убедитесь, что вы не делаете при прокрутке ничего, что фактически изменит/анимирует размер самой страницы (например, анимируете свойство высоты элемента в потоке документа).
  6. Минимизируйте область изменения. Представьте, что вы рисуете прямоугольник вокруг общей области, которую пиксели изменяют на каждом такте — чем больше этот прямоугольник, тем сложнее браузеру его отрисовывать. Опять же, это не имеет никакого отношения к GSAP — это чисто графическое отображение в браузере. Поэтому будьте стратегически настроены в том, как вы создаете свои анимации, и старайтесь, чтобы области изменения были как можно меньше.
  7. Если вы анимируете отдельные части графики SVG, это может быть затратно для браузера на рендеринг. SVG должны динамически изготавливать каждый пиксель с использованием математики. Если это статический SVG, который вы просто перемещаете (целиком), это нормально — браузер может растеризовать его и просто распихать эти пиксели... но если внутренности SVG меняются, это совсем другая история. 
  8. Задержка данных — довольно дорогой эффект, FYI. Конечно, мы оптимизируем его по мере возможности, но сама его природа очень динамична и требует определенного объема обработки для корректной обработки.
  9. Я бы рекомендовал стратегически отключить определенные эффекты/анимацию, а затем перезагрузить игру на ноутбуке и просто посмотреть, будет ли разница (если вообще будет). 

В конечном счете, не существует универсального решения, вроде «включите это одно свойство и чудесным образом заставьте суперсложный сайт с большим количеством графики работать идеально гладко даже на 8-летних телефонах». 

 

Наконец, вы можете проверить плагин Observer, так как он кажется лучшей альтернативой для того, чего вы пытаетесь добиться здесь:

 

 

 

Надеюсь, это поможет.

Счастливого твининга!

I don't really understand how to apply it to my case. 
I don't really understand why such jerks occur, although the code is as simple as possible and there are only 4 images. 

Do you have any specific recommendations for me?
Observer will only change the processing of scrolling and swipes, but the transition through the sections will still be the same as I have now. 
 

 

Posted

Yeah the code is super simple and there are just a few images, the issue is not the code is the rendering phase by the browser what is causing the performance bottleneck. Code itself is rarely the cause of performance issues, 99.9% of the times is rendering.

 

Try will-change: transform in the elements that are being animated and see if that improves performance in some way:

https://developer.mozilla.org/en-US/docs/Web/CSS/will-change

 

30 minutes ago, Yakiv said:

I don't really understand how to apply it to my case. 

I'd recommend you to explore the Observer Plugin docs and study that demo:

https://gsap.com/docs/v3/Plugins/Observer/

 

Also check the demos in this collection in order to get a better grasp of how the plugin works:

https://codepen.io/collection/xKoPmy

 

Hopefully this helps

Happy Tweening!

Posted
5 minutes ago, Rodrigo said:

Yeah the code is super simple and there are just a few images, the issue is not the code is the rendering phase by the browser what is causing the performance bottleneck. Code itself is rarely the cause of performance issues, 99.9% of the times is rendering.

 

Try will-change: transform in the elements that are being animated and see if that improves performance in some way:

https://developer.mozilla.org/en-US/docs/Web/CSS/will-change

 

I'd recommend you to explore the Observer Plugin docs and study that demo:

https://gsap.com/docs/v3/Plugins/Observer/

 

Also check the demos in this collection in order to get a better grasp of how the plugin works:

https://codepen.io/collection/xKoPmy

 

Hopefully this helps

Happy Tweening!

I've tried the will-change: transform and it doesn't change anything. 

Posted

Yeah, the will-change property should be added to the images you're animating. If that doesn't help, try with smaller images, with less KB size and smaller DPI.

 

Beyond that I'm afraid that there is no much we can do to help, as mentioned this is a rendering issue and not a GSAP related issue. If that was the case half of the developers that tween images with GSAP would be reporting issues.

 

Sorry I can't be of more assistance 😞

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...