Jump to content
Search Community

I want my gsap animations to run after specific image is loaded, is there anything else I can use instead of window.addEventListener('load')?

kisha test
Moderator Tag

Recommended Posts

Hi, well title is the question.

I dont want to use window.addEventListener('load') because I dont want to wait for everything to be loaded, but just for the image which is in viewport when website is loaded...(image is set as css background)

Is there any vanilla JS or greensock solution, or I need to use something like https://imagesloaded.desandro.com/

Link to comment
Share on other sites

13 minutes ago, tailbreezy said:

Hello kisha,

 

I haven't used an event listener on a single image, but I do believe you can check by attaching the eventListener on the image itself.

 


img.addEventListener( "load", () => { /* code */ })

 

Hi and thanks for commenting.
That seems like it's working if my image is in HTML, but I set it as background-image in CSS, and it doesn't work this way

Link to comment
Share on other sites

1 hour ago, tailbreezy said:

You can check when image is loaded and then simply add it as a background with 


HTMLelem.style.backgroundImage

 

or simply toggle a class on load.

I see, am I suppose to hide the image that is added with <img> tag with with display: none;? Because I just want to show it as background. Im guessing that's the trick?

I'm not sure what you mean by toggling a class on load but I will look into it

Link to comment
Share on other sites

On 2/28/2021 at 5:46 PM, kisha said:

I see, am I suppose to hide the image that is added with <img> tag with with display: none;? Because I just want to show it as background. Im guessing that's the trick?

Why not just use the img positioned as such that it replaces css background? That way you gain the benefit of potentially better seo and accessibility and responsive sizes. With object-fit, I find I rarely need to use background-image any more.

  • Like 1
Link to comment
Share on other sites

On 3/1/2021 at 7:32 AM, tailbreezy said:

 

Not necessarily. You can create new Image() that is not part of the DOM and attach onload and src on it.

var myImage = new Image();

myImage.src = 'src/images/img.jpg';



myImage.addEventListener('load', function() {

init()

}

I done this and it works. Thank you

Link to comment
Share on other sites

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...