Monday, May 26, 2014

ng-threshold: an angular directive for easy image fallback


Grab the source code on GitHub 

A few weeks ago, my friend and colleague Maurice drew my attention to this article on Forbesfollowing the facebook outage that slowed quite a few websites down. This lead us to think: why not define a maximum amount of time to every image or resource that we try to load from a web server? this turned out to be ng-threshold, a nice little angular directive to accomplish just that.

from the GitHub page of ng-threshold:

ng-threshold

ng-threshold is a simple angular.js directive that allows you to specify the maximum amount of allowed time for an image to load. If the image fails to load because the maximum amount of time has elapsed or because the image failed to load immediatly (because of a 404 error, for example), a fallback image is loaded instead.

How to use

  1. include the ng-threshold.js directive in your index file
  2. anywhere in the scope of the app, use the 'threshold' attribute to specify this is an image to be used with ng-threshold
  3. specify data-src-maxtime in milliseconds (maximum time to wait for the original image src to load)
  4. specify data-src-fallback (this is your fallback URL in case the original image does not load)

Example

<!doctype html>
<html>
<head>
<body ng-app="myAngularApp">
    <img  src="http://slow-server.not.really/this_image_takes_more_than_5_sec_to_load.jpg" 
    data-src-fallback="https://www.google.com/images/srpr/logo11w.png" 
    data-src-maxtime="5000" 
    threshold=""/>
  </div>

No comments:

Post a Comment