Created
May 6, 2011 22:37
-
-
Save joshellington/959933 to your computer and use it in GitHub Desktop.
Preload background-images from media query CSS files
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
function preload(arrayOfImages) { | |
$(arrayOfImages).each(function(){ | |
// Find 4 digit pixel reference in filename | |
var digits = 4; | |
var str = this; | |
var regex = new RegExp("\\d{"+digits+"}", "g"); | |
var match = str.match(regex); | |
// If bg image is smaller than user's screen width | |
if ( match < screen.width ) { | |
(new Image()).src = this; | |
} | |
}); | |
} | |
function getBgImages(selector, cssFile) { | |
var styles, imgs = []; | |
// Find specified stylesheet | |
$.each(document.styleSheets, function(i,sheet) { | |
var reg = new RegExp(cssFile, 'g'); | |
var results = reg.test(sheet.href); | |
if ( results ) { | |
styles = sheet.rules || sheet.cssRules; | |
} | |
}); | |
// Loop through stylesheet and look for selector | |
$.each(styles, function(i,item) { | |
// If style href equals css file argument | |
if ( item.parentStyleSheet['href'] == cssFile ) { | |
// Loop through rules | |
$.each(item.parentStyleSheet.cssRules, function(i,v) { | |
if ( v.selectorText == selector ) { | |
var css = v.cssText; | |
var bg = css.match(/url\([^)]+\)/g); | |
$.each(bg, function(i,v) { | |
var img = v.replace('url(', ''); | |
img = img.replace(')', ''); | |
imgs.push(img); | |
}); | |
} | |
}); | |
} | |
}); | |
return imgs; | |
} | |
// Preloader | |
$(window).load(function() { | |
var cssFiles = $('link[media]'), files = {}; | |
$.each(cssFiles, function(i,item) { | |
// Find 4 digit pixel reference in filename | |
var digits = 4; | |
var str = item.href; | |
var regex = new RegExp("\\d{"+digits+"}", "g"); | |
var match = str.match(regex); | |
if ( match == null ) | |
match = 0; | |
if ( item.media != 'all' ) | |
files[match] = item.href; | |
}); | |
var bodyClass = '.'+$('body').attr('class'); | |
// Preload background images referenced by body class | |
$.each(files, function(k,v) { | |
if ( screen.width > k ) | |
preload(getBgImages(bodyClass+' div#background', v)); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment