/*jshint noarg:true, noempty:true, bitwise:true, strict:true, undef:true, unused:true, curly:true, browser:true, devel:true, jquery:true, nomen:false, onevar:false */ (function () { 'use strict'; // all images ending with '?processing' will show a loading icon and calls // will be repeatedly made to the end URL until the file is loaded var ImageLoader = function (images, options) { var _images, _timer, _tempImg, _attempts = 0, _defaults = { containerClass: 'image-loading', delay: 1000, maxAttempts: 30 // number of attempts before cancelling }, _options = $.extend(_defaults, options); var _load = function () { var date = new Date(), url = _images.attr('src'); // add the date time so the browsers do not cache the 404 error url += url.indexOf('?') >= 0 ? '&' : '?'; url += date.getTime(); _attempts++; _tempImg = new Image(); _tempImg.addEventListener('load', _loadComplete, false); _tempImg.addEventListener('error', _loadFailed, false); _tempImg.src = url; }; var _loadComplete = function (evt) { // get the URL from the target var url = $(evt.target).attr('src'); _images.unwrap(); _images.attr('src', url); _images.css('visibility', 'visible'); _images.trigger('imageloader.load'); }; var _loadFailed = function () { if (_attempts >= _options.maxAttempts) { _images.trigger('imageloader.error'); } else { _timer = setTimeout(_load, _options.delay); } }; // init (function () { _images = $(images); _images.css('visibility', 'hidden'); _images.each(function () { var width, height, container, img = $(this); // wrap the img in a div img.wrap($('
')); container = img.parent().addClass(_options.containerClass); // attempt to get the height and width width = img.attr('width'); height = img.attr('height'); if (width && height) { container.css({ width: width, height: height, maxWidth: '100%' }); } }); // attempt to load again in moment _timer = setTimeout(_load, _options.delay); }()); }; $.fn.imageloading = function (options) { var imagesWithUniqueUrls = {}, src; this.each(function () { var img = $(this), src = img.attr('src'); if (!imagesWithUniqueUrls[src]) { imagesWithUniqueUrls[src] = []; } imagesWithUniqueUrls[src].push(this); }); for (src in imagesWithUniqueUrls) { if (imagesWithUniqueUrls.hasOwnProperty(src)) { new ImageLoader(imagesWithUniqueUrls[src], options); } } return this; }; }()); $('img[src$="?processing"]').imageloading(); $('img[src$="?processing"]').on('imageloader.load', function() { var el = $(this); el.parent().find('span.processing').remove(); });