Search code examples
javascriptiosiphoneimageonload-event

Image load event not triggering on iPhone (IOS)


I have a very simple code snippet to set a background image of an element once the image has loaded on a new image object.

var img = new Image();
var myelement = document.getElementById('myelement_id');
img.addEventListener('load', function(){
  myelement.setAttribute('style', 'background-image: url(/public/images/myimage.jpg)');
});
img.src = '/public/images/myelement.jpg';

This question has already been asked a few times but answers have not been satisfying.

It's not the size of the image. The load event isn't fired no matter the size or format of the image.

The error event is not fired neither. Some people suggested that the error event will be fired instead of the load event on IOS.

It's not the browser. It's IOS. The behaviour is the same on Safari or Chrome on IOS.

It's not observable with BrowserStack. The image loads fine on BrowserStack yet a physical device is incapable of firing the load event.

I do assign the function first and thereafter set src to trigger the load event.


Solution

  • This seems to be working for me. But I am not sure whether changing the add event listener to the .load event made the difference.

    function imgLoad(_imgDOM, _imgID){
      _imgDOM.setAttribute('style', 'background-image: url(/public/images/load/' + _imgID + '.jpg)');
    }
    
    var imgLoadArray = document.querySelectorAll('.img__load');
    
    for (var i = 0; i < imgLoadArray.length; i++) {
      var imgDOM = imgLoadArray[i];
      var imgID = imgDOM.getAttribute('id');
      var img = new Image();
      img.onload = imgLoad(imgDOM, imgID);
      img.src = '/public/images/load/' + imgID + '.jpg';
    }