Skip to content

Instantly share code, notes, and snippets.

@joshellington
Created May 6, 2011 22:37
Show Gist options
  • Save joshellington/959933 to your computer and use it in GitHub Desktop.
Save joshellington/959933 to your computer and use it in GitHub Desktop.
Preload background-images from media query CSS files
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