Hello Everyone!
I have a bit of a generic problem/misunderstanding - basically, i have some animations in GSAP and have a couple of questions to understand it more deeply:
When is the best time to load the GSAP animation (when the document is loaded or when everything is loaded (DOM, images, etc))?
The first question leads to this one - if I do a hard refresh in the browser my animations are flashing or for example, the element that should be x: -100% is visible (for literally like 0.00s but still and then animation kicks in so there is a little flash) because the js file is not probably loaded yet - how do you guys tackle this, especially vital animations like for hero section or the other places when we need everything to be loaded and animated ASAP?
Please have a look at the code below all bundled by webpack:
$(function () {
// Hero section animation
const heroBanners = document.querySelectorAll(".section__hero-banner");
heroBanners.forEach((section) => {
let imgCover = section.querySelector(".img-cover");
let imgTl = gsap.timeline({
scrollTrigger: {
trigger: section,
// markers: {startColor: "green", endColor: "red", fontSize: "18px", fontWeight: "bold", indent: 20},
start: "top center",
},
});
// Inital state for headings
imgTl.set(".hero-text__right", {x: "120%"});
imgTl.set(".hero-text__left", {x: "-120%"});
imgTl.to(imgCover, {
opacity: 1,
ease: "power4.inOut",
duration: 0.4,
});
gsap.utils.toArray(section.getElementsByClassName("hero-text")).forEach((heroText, herIdx) => {
var container = section.getElementsByClassName("text-wrapper");
let textTl = gsap.timeline({
scrollTrigger: {
trigger: section,
scrub: 1,
// markers: {startColor: "green", endColor: "red", fontSize: "18px", fontWeight: "bold", indent: 20},
start: "top top-=50px",
end: "bottom center",
// toggleActions: "restart none none reset"
},
});
if (herIdx % 2 == 0) {
let distance = $(container).width() - $(heroText).width();
//left
imgTl.to(heroText, {
x: "0%",
duration: 0.85,
ease: "power4.inOut",
});
textTl.to(heroText, {
x: `${distance}px`,
});
} else {
let distance = $(container).width() - $(heroText).width();
//right
imgTl.to(
heroText,
{
x: "0%",
duration: 0.85,
ease: "power4.inOut",
delay: -0.85,
}
);
textTl.to(heroText, {
x: `-${distance}px`,
});
}
});
});
});
The animation is: hero image fade in then slide two lines of text from left and right.
Would be amazing he somebody could point out some bad practises or mistakes or if this could be done in better way.
thanks you so much guyz!