Created
December 1, 2012 12:42
-
-
Save jayarjo/4182073 to your computer and use it in GitHub Desktop.
Preload Images
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// preload images | |
function preloadImages() { | |
var items = [], current = 0, errors = [], timer; | |
var resetTimer = function() { | |
stopTimer(); | |
startTimer(); | |
}; | |
var stopTimer = function() { | |
if (timer) { | |
clearTimeout(timer); | |
} | |
}; | |
var startTimer = function() { | |
// if process for some reason gets stuck, forcefully finish it all | |
timer = setTimeout(function() { | |
onProgress(100); | |
onComplete(); | |
}, 10000); | |
}; | |
var getImages = function(element) { | |
$(element).find('*:not(script,link,style,meta,head,title)').each(function() { | |
var url = ""; | |
if ($(this).css('background-image').indexOf('none') == -1) { | |
url = $(this).css('background-image'); | |
if(url.indexOf('url') != -1) { | |
var temp = url.match(/url\((.*?)\)/); | |
url = temp[1].replace(/\"/g, ''); | |
} | |
} else if ($(this).get(0).nodeName.toLowerCase() == 'img' && typeof($(this).attr('src')) != undefined) { | |
url = $(this).attr('src'); | |
} | |
if (url.length > 0 && $.inArray(url, items) < 0) { | |
items.push(url); | |
} | |
}); | |
} | |
//create preloaded image | |
var preloading = function() { | |
var queue = []; | |
for (var url in items) { | |
loadImg(url); | |
} | |
startTimer(); | |
}; | |
var loadImg = function(url) { | |
var imgLoad = new Image(); | |
imgLoad.onload = completeLoading; | |
imgLoad.onerror = completeLoading; | |
imgLoad.src = url; | |
}; | |
//update progress bar once image loaded | |
var completeLoading = function() { | |
current++; | |
var per = Math.round((current / (items.length || 1)) * 100); | |
//if all images loaded | |
if(current >= items.length) { | |
current = items.length; | |
onProgress(100); | |
onComplete(); | |
} else { | |
onProgress(per); | |
} | |
}; | |
function onComplete() { | |
stopTimer(); | |
} | |
function onProgress(per) { | |
resetTimer(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment