luis-almeida / unveil

A very lightweight jQuery plugin to lazy load images
4.16k stars 676 forks source link

fall back to a default image when the image src is invalid #141

Open tzws opened 7 years ago

tzws commented 7 years ago

sometimes, the src of image retrieved from server is just invalid. Either, the src is just empty, or the image on the server was deleted somehow.

On these cases, the html either rendered on server side, or rendered by front end such as Vue.js, etc, it's better to fallback to a default image, for example, a defualt image.

The related issues are: #91 and #70

the code is simple, add a config option:

  $.fn.unveil = function(threshold, callback, errorSrc) {

and, some code to handle src is null, or src is invalid

    this.one("unveil", function() {
      var source = this.getAttribute(attrib);
      source = source || this.getAttribute("data-src");
      if (source) {
        this.setAttribute("src", source);
        if (typeof callback === "function") callback.call(this);
      } else if(errorSrc){

          this.setAttribute("src", errorSrc);
      }
      this.onerror = function () {
          if(errorSrc)
          {
              this.setAttribute("src", errorSrc);
          }
      }
    });

And when calling the plugin, you may:

    $(function() {
        $("li img").unveil(300, null, "http://lorempixel.com/g/800/500/city/7/");
    });

the third parameter is the fallback src.

and here's the html:

    <ul>
        <!-- empty src -->
        <li><img data-src="" data-src-retina="" src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" /></li>

        <!-- invalid src -->
        <li><img data-src="http://lorempixel.com/does-not-exists" data-src-retina="http://lorempixel.com/does-not-exists" src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" /></li>
    </ul>