$lazybg

Lazy loading of background-image in stylesheets

dist/lazybg.js enables to lazy load background images in stylesheets. It makes use of CSS Variables with a fallback for old browsers.
There are four options to resolve images:
  1. 1.
    manually define images via :root {} within the stylesheet
  2. 2.
    base64 encode image URLs
  3. 3.
    provide a JSON source list as resolver
  4. 4.
    provide a javascript function as resolver
1
/* :root based pre-configured value */
2
:root {
3
--z--lazy-img: url('/image.jpg');
4
}
5
footer {
6
background-image: url('/image.jpg'); // old browsers
7
background-image: var(--z-lazy-img, none);
8
}
9
10
/* base64 encoded value */
11
p#out-of-view {
12
background-image: url('/image.jpg'); // old browsers
13
background-image: var(--z-base64_value, none); /* note: requires character replacements, see documentation */
14
}
15
16
/* JSON object or javascript function based custom resolver */
17
div#out-of-view {
18
background-image: url('/image.jpg'); // old browsers
19
background-image: var(--z-custom-resolved, none);
20
}
Copied!
1
<script src="dist/lazybg.js"></script>
2
<script>
3
// default: document.styleSheets
4
$lazybg();
5
6
// custom $lazy config
7
$lazybg(
8
document.querySelectorAll('link[rel=stylesheet], style#other'),
9
{
10
observer: {
11
threshold: 0,
12
rootMargin: '100px'
13
}
14
}
15
);
16
17
// custom JSON based resolver
18
$lazybg(
19
0,0, // default config
20
21
// resolver
22
{
23
"custom-resolved": "url('/image.jpg')"
24
}
25
);
26
27
// custom javascript based resolver
28
$lazybg(
29
0,0, // default config
30
31
// resolver
32
function(key) {
33
34
// resolve key "custon-resolved"
35
return "url('/"+key+".jpg');"
36
}
37
);
38
</script>
Copied!

Base64 encoded image value

CSS variables are limited to DOMString. The following characters need to be replaced in a base64 encoded value:
/:
=:
Last modified 2yr ago