skip to Main Content

I’m trying over my computer to make a lazyloader for images that dynamically replaces the css value background-image with the attribute data-bgimg

The code for doing this it’s very simple.
See below:

$(document).ready(function(){
$('.lazyloadbg').each(function(i, e) {
if ($(e).attr('data-bgimg')) {
    $(e).css({ "background-image": "url('" + $(e).attr('data-bgimg') + "')"    });
}
});
});

So when there is an element with the class lazyloadbg like this

<div class="lazyloadbg" data-bgimg="/something.jpg">
</div>

the background image it’s replaced dinamically after the page code loading.


Now the question.

For big images (as you can see from this image linked) the image becomes corrupted and I got an error called "NS_ERROR_NET_PARTIAL_TRANSFER".

NS_ERROR_NET_PARTIAL_TRANSFER

The image extrabig was made ad hoc for testing (it’s over 50MB).

Now, how to detect if the image it’s corrupted?

I tryied something like

    document.addEventListener('error', e => {
        if (e.target.matches('img')) {
        console.log(e.type, e.target, e);
        } else if (e.target.matches('script'))  {
            //do nothing
        } else if (e.target.matches('style'))  {
            //do nothing
        } else if (e.target.matches('link'))  {
            //do nothing
        } else if (e.target.matches('iframe'))  {
            //do nothing
        } else {
            console.log(e.type, e.target, e);
        }
    }, true);
    
    document.addEventListener('load', e => {
        if (e.target.matches('img')) {
        console.log(e.type, e.target, e);
        } else if (e.target.matches('script'))  {
            //do nothing
        } else if (e.target.matches('style'))  {
            //do nothing
        } else if (e.target.matches('link'))  {
            //do nothing
        } else if (e.target.matches('iframe'))  {
            //do nothing
        } else {
            console.log(e.type, e.target, e);
        }
    }, true);

but the error and also the loading are not detected as event (I’m talking about the background-image change in style).

So how to solve this?

P.S. I even tried it too like in this answer How to detect broken CSS background images?

    const items = document.querySelectorAll('.lazyloadbg');

    items.forEach((item) => {
      const imageURL = window.getComputedStyle(item).getPropertyValue('background-image');
      const rgURL = /url(['|"](.+)['|"])/gi;
      const imgSrc = (rgURL).exec(imageURL)[1];
      const img = document.createElement('img');

      img.setAttribute('src', imgSrc);  
      img.addEventListener('error', ({ target }) => {
        console.warn(`${target.src} is not found`);
        item.style.borderColor = 'red';
      })
    });

but the event that should be fired it’s not triggered.

2

Answers


  1. yout can try something like this:

         const items = document.querySelectorAll('.lazyloadbg');
    
    function loadImages() {
        const promises = [];
        items.forEach((image) => {
            promises.push(new Promise((resolve, reject) => {
                image.onload = () => resolve(image.src);
                image.onerror = () => reject();
            }));
        });
        return Promise.allSettled(promises)//return all promises, rejected or resolver
    };
    
    loadImages().then((imageUrl) => {
        //Do something when load success
    })
    .catch(()=>{
        //Do something when load  throws error
    })
    
    Login or Signup to reply.
  2. It seems like you are trying to detect and handle errors for background images set using the background-image property via JavaScript. Unfortunately, the error and load events typically associated with the tag are not applicable to background images set in CSS.

    One approach to handle this is by preloading the images using JavaScript, and then checking for errors during the preloading process. Here’s an example using your code:

    $(document).ready(function () {
        $('.lazyloadbg').each(function (i, e) {
            if ($(e).attr('data-bgimg')) {
                // Create a new Image object
                var img = new Image();
                
                // Set the source to the data-bgimg attribute
                img.src = $(e).attr('data-bgimg');
                
                // Handle the load event
                img.onload = function () {
                    // Image loaded successfully, update the background-image
                    $(e).css({ "background-image": "url('" + img.src + "')" });
                };
                
                // Handle the error event
                img.onerror = function () {
                    // Image failed to load, handle the error here
                    console.error("Failed to load image: " + img.src);
                };
            }
        });
    });
    

    In this example, an Image object is created for each .lazyloadbg element, and the onload and onerror events are used to handle success and failure cases, respectively. This way, you can catch errors during the preloading process and take appropriate actions.

    Keep in mind that preloading images might increase the initial loading time of your page, especially if there are many large images. Consider optimizing your images or implementing a more advanced lazy-loading solution if performance is a concern.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search