define([], function(){ var AutoPreloader = function(context){ this.s = $.extend({ targetElement:$("body"), backgroundImageRegEx: /(?:\(['|"]?)(.*?)(?:['|"]?\))/, knownImages:{}, preloaderImageHolder:$(""), images:null, loadedCount:0 }, this); this.s.targetElement.append(this.s.preloaderImageHolder); this.findBGImages(); this.findImages(); //console.log("this.s.knownImages",this.s.knownImages) this.run(); } AutoPreloader.prototype.findImages = function(){ this.s.allImages = $("img"); this.s.allImages.each($.proxy(function(index, el){ var image = $(el); if(image.attr("src")){ this.s.knownImages[image.attr("src")] = false; image.addClass("preload-image"); } },this)); this.s.images = $("img.preload-image"); } AutoPreloader.prototype.findBGImages = function(){ $("*").each($.proxy(function(index, el){ var bgProp = $(el).css("background-image"); extracterUrl = this.s.backgroundImageRegEx.exec(bgProp); if(extracterUrl && (extracterUrl[1].indexOf("png") != -1 || extracterUrl[1].indexOf("jpg") != -1)){ this.s.knownImages[extracterUrl[1]] = false; } },this)); for(var url in this.s.knownImages){ var img = $(""); img.attr("src",url); this.s.preloaderImageHolder.append(img); } } AutoPreloader.prototype.onCardLoadOrError = function(evt){ var img = $(evt.currentTarget); this.s.knownImages[img.attr("src")] = true; this.s.loadedCount++; //console.log("loaded",this.s.loadedCount , "of", this.s.images.length, (this.s.loadedCount/this.s.images.length)+"%"); //loadingBarFill.css({ // width:(this.s.loadedCount/this.s.loadedCount.length*100)+"%" //}); //console.log("TRIGGER",this.s.targetElement) this.s.targetElement.trigger("imageLoaded", { image:img.attr("src"), loaded:this.s.loadedCount, total:this.s.images.length, percent:(this.s.loadedCount/this.s.images.length*100) }); if(this.s.loadedCount == this.s.images.length-5){ //if(this.s.loadedCount == this.s.images.length){ //console.log("TRIGGER COMPLETE",this.s.targetElement) this.s.targetElement.trigger("preloadComplete", { loaded:this.s.loadedCount, total:this.s.images.length, percent:(this.s.loadedCount/this.s.images.length*100) }); } //console.log("AutoPreloader.onCardLoadOrError " + this.s.loadedCount + " of " + this.s.images.length, evt) } AutoPreloader.prototype.run = function(){ //console.log("AutoPreloader.run") var numberNotAlreadyLoaded = 0; this.s.images.error($.proxy(this.onCardLoadOrError,this)).one("load", $.proxy(this.onCardLoadOrError,this)).each(function() { if(this.complete) $(this).load(); else numberNotAlreadyLoaded++; }); if(numberNotAlreadyLoaded > 1){ this.s.targetElement.trigger("stuffToLoad"); } } return AutoPreloader; });