Skip to content

Instantly share code, notes, and snippets.

@tito10047
Last active July 23, 2017 11:10
Show Gist options
  • Select an option

  • Save tito10047/0b293cff00ae908a0403e92245cc3239 to your computer and use it in GitHub Desktop.

Select an option

Save tito10047/0b293cff00ae908a0403e92245cc3239 to your computer and use it in GitHub Desktop.
preload css images
function createStyle(css) {
var head = document.head || document.getElementsByTagName('head')[0],
style = document.createElement('style');
style.type = 'text/css';
if (style.styleSheet) {
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
head.appendChild(style);
}
var __preloaderIds = 1;
function preloadStyleImages(images) {
var total=0;
var lastTime=5000;
while(true) {
var div = document.createElement('div');
div.id = "css-preloader-" + __preloaderIds;
__preloaderIds++;
document.getElementsByTagName("body")[0].appendChild(div);
var style = "#" + div.id + ":after{\n\tposition:absolute; width:0; height:0; overflow:hidden; z-index:-1;\n\tcontent:\n";
for (var i = 0; i<15 && total < images.length; i++,total++) {
style += "\turl('" + images[total] + "')";
if (i === images.length - 1) {
style += ";";
}
style += "\n";
}
style += "}";
setTimeout((function(style){
return function(){
createStyle(style);
}
})(style),lastTime);
lastTime+=100;
if (total===images.length){
break;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment