-
-
Save MohamedAlaa/11086309 to your computer and use it in GitHub Desktop.
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($) { | |
function parseImagesFromCSS(doc) { | |
var i, j, | |
rule, | |
image, | |
pattern = /url\((.*)\)/, | |
properties = ['background-image', '-webkit-border-image'], | |
images = {}; | |
if (doc.styleSheets) { | |
for (i = 0; i < doc.styleSheets.length; ++i) { | |
images = $.extend(images, parseImagesFromCSS(doc.styleSheets[i])); | |
} | |
} else if (doc.cssRules) { | |
for (i = 0; i < doc.cssRules.length; ++i) { | |
rule = doc.cssRules[i]; | |
if (rule.styleSheet) { | |
images = $.extend(images, parseImagesFromCSS(rule.styleSheet)); | |
} else if (rule.style) { | |
for (j=0; j < properties.length; j++) { | |
image = pattern.exec(rule.style.getPropertyValue(properties[j])); | |
if (image && image.length === 2) { | |
images[image[1]] = image[0]; | |
} | |
} | |
} | |
} | |
} | |
return images; | |
}; | |
$.extend({ | |
preload: { | |
images: function(doc) { | |
doc = doc || document; | |
var images = $.map(parseImagesFromCSS(doc), function(url) { return url; }), | |
head = doc.getElementsByTagName('head')[0], | |
style = doc.createElement('style'); | |
style.type = 'text/css'; | |
style.id = 'preload'; | |
style.innerHTML = 'body::after { content: ' + images.join(' ') + '; display: none; }'; | |
head.appendChild(style); | |
} | |
} | |
}); | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Function parseImagesFromCSS(doc):
This function traverses the CSS stylesheets of a given document to extract image URLs from specific CSS properties.
It looks for background-image and -webkit-border-image.
Regular Expression:
The pattern /url((.*))/ is used to match and extract the URL from the CSS property values.
Recursion:
The function handles both the top-level stylesheets and any nested stylesheets (like those defined within @import rules).
Image Collection:
It collects all unique image URLs in an object and returns it.
Preload Functionality:
The $.extend() method adds a preload method to jQuery, which, when called, gathers all image URLs and creates a <style> element that uses ::after pseudo-element to preload these images without displaying them.
official website tap road game