htmlimagesrcset

is possible when img srcset not loaded, then fallback img src?


I know the fallback image is used when none of sources matches the attribute media.

However, I am trying to do if the media is matched but the scrset wasn't loaded, then the fallback img will be load in case my image somehow missing at least the fallback could be a backup.

or is there any method can be suit this situation?

<picture>
	<source media="(min-width: 320px)" srcset="/img/not-exist.jpg">
	<img src="https://images.unsplash.com/photo-1519455953755-af066f52f1a6?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=634&q=80" alt="this is img">
</picture> 


Solution

  • This link will be helpful HTMLImageElement.complete

    And see a solution here. Note that if the srcset does not load I have set the srcset and src attributes equal to the img src attribute, that way on window resize it does not try to load the missing srcset attribute again. You would also want to update the logic to check for viewport width I am sure, and you could incorporate lodash to debounce, but hopefully this will get you pointed in the right direction:

    window.onload = function(){
      var parent = document.getElementById("parent-element");
      var source = parent.querySelector("source");
      var img = parent.querySelector("img");
      var srcset = source.getAttribute("srcset");
      var src = img.getAttribute("src");
      if(!srcset.complete){
        source.setAttribute("srcset", src);
        img.setAttribute("src", src);
      }
    }
    <picture id="parent-element">
    	<source media="(min-width: 320px)" srcset="/img/not-exist.jpg">
    	<img src="https://images2.minutemediacdn.com/image/upload/c_fill,g_auto,h_1248,w_2220/v1584388937/shape/mentalfloss/536413-gettyimages-1077470274.jpg?itok=NoDcW5uz" alt="this is img">
    </picture>