Skip to content

Conversation

@tzws
Copy link

@tzws tzws commented May 31, 2017

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>

@tzws tzws mentioned this pull request Jun 1, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant