Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
wants to merge 3 commits into
base: master
Choose a base branch
from

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