javascriptjqueryanimationwebp

Redisplaying an already loaded animated WEBP image from the beginning


There is a problem: when initially loading an animated webp image on the page, everything works correctly. The image is loaded and when the loading is completed, it is displayed from the beginning of the animation. The animation of the image is looped, which means that it continues to play even when I hide it from the page (the CSS class is removed). It is inserted as a background image to the DIV element. If it is necessary to display the animation again, I add a class back to the div, but the animation does not play from the beginning, but from the moment in which the animation is since the initial load. I use jQuery on ерш page.

A working option is to add a random value to the end of the URL to the image, but this means reloading it from server again, and there are a lot of animated webp images on the page and they weigh quite a lot (about a 1 megabyte), which excludes the use of this method for people with slow Internet.

Dear experts, tell me, are there any cases to emulate the loading of an already loaded image in the browser and play the animation from the beginning? It is highly desirable to solve the problem without resorting to cumbersome third-party plugins. First of all, I want to understand the essence of the solution, and not load a huge plugin and get a quick but incomprehensible result.

now i research some constructions like this, but no good result yet

let promise     = this.load_image('/images/' + image_url, img);

promise.then((res) => {
    this.loaded(); // отображаем изображение
});

load_image: async function(url, elem)
{
    return new Promise((resolve, reject) => {
        elem.onload = () => resolve(elem);
        elem.onerror = reject;
        elem.src = url;
    });
}```

Solution

  • So this seems to be as easy as setting the src to "", however I had a bit more luck using a setTimeout

    Here is the function I used to do this;

    function restartWEBP(img){
        var src = img.src; 
        img.src = ""; 
        setTimeout(function(){
            img.src = src; 
        }, 1); 
    };