@quiql/lazy 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +347 -3
- package/dist/quiql-lazy.d.ts +200 -0
- package/dist/quiql-lazy.js +528 -0
- package/dist/quiql-lazy.min.js +1 -0
- package/package.json +44 -6
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 WebSultan
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,347 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
<div align="center">
|
|
2
|
+
<img src="https://raw.githubusercontent.com/quiql/lazy/main/logo.png" alt="Quiql Logo" width="84" />
|
|
3
|
+
<h1>Quiql Lazy</h1>
|
|
4
|
+
<p><em>Quick eQuals Quality</em></p>
|
|
5
|
+
<p>
|
|
6
|
+
<a href="https://github.com/quiql/lazy/blob/main/LICENSE">
|
|
7
|
+
<img src="https://shields.io/badge/license-MIT-00cc66?style=flat-square" alt="License: MIT" />
|
|
8
|
+
</a>
|
|
9
|
+
</p>
|
|
10
|
+
</div>
|
|
11
|
+
|
|
12
|
+
**Quiql Lazy** is an ultra-lightweight, zero-dependency JavaScript library for lazy loading media (`<img>`, background images) and dynamically loading external resources (`<script>`, `<link>`, etc.) with built-in **request deduplication**, **DOM caching**, and `IntersectionObserver` support — engineered for **Core Web Vitals** and **Green IT**.
|
|
13
|
+
|
|
14
|
+
## Features
|
|
15
|
+
|
|
16
|
+
* **Media Lazy Loading (`LazyLoad`)**: Out-of-the-box support for `<img>` (`src`, `srcset`, `sizes`) and background images (`data-bg`) with automatic state CSS classes (`lazy`, `loading`, `loaded`, `error`).
|
|
17
|
+
* **Custom Viewport Triggers (`CustomLoad`)**: Execute any custom logic (analytics, animations, third-party widgets) when elements enter the viewport.
|
|
18
|
+
* **Resource Loader (`loadScript`, `loadStyle`, `loadResource`)**: Dynamically inject scripts, stylesheets, or any HTML tags into the DOM with Promise support.
|
|
19
|
+
* **Request Deduplication & Caching**: Prevents duplicate network requests if the same resource is requested multiple times simultaneously or sequentially.
|
|
20
|
+
* **Existing DOM Scanner**: Optionally scans already loaded `<script>` and `<link>` tags on the page to avoid reloading them.
|
|
21
|
+
* **SSR Safe & Fallback Ready**: Safely runs in Node.js/SSR environments and gracefully falls back in legacy browsers without `IntersectionObserver`.
|
|
22
|
+
|
|
23
|
+
## Green IT & Performance Impact (Honest Benchmark)
|
|
24
|
+
|
|
25
|
+
Pure lazy loading does not eliminate data transfer if a user scrolls through the entire page — in that case, network and CPU usage are simply shifted over time to keep the initial load fast and responsive.
|
|
26
|
+
|
|
27
|
+
**Real energy and traffic savings come from two sources:**
|
|
28
|
+
1. **Partial Scrolls & Early Bounces:** Web analytics consistently show that a large share of visitors bounce early, navigate away from the top viewport, or scroll only halfway down. Every image or interactive widget (such as a slider, map, or video embed) below the fold that never enters the viewport is **never downloaded, never decoded, and never parsed by the browser's Main Thread**.
|
|
29
|
+
2. **Eliminating Duplicate Resource Fetches:** Even when a user scrolls 100% of the page, independent components (such as multiple forms loading reCAPTCHA, map embeds, or slider libraries) often trigger redundant script requests. Built-in Promise caching and DOM scanning guarantee each external asset is downloaded **strictly once**.
|
|
30
|
+
|
|
31
|
+
### 📊 Conservative Case Study (1,000,000 Page Views / Day)
|
|
32
|
+
Consider a modern, optimized website (using WebP images and Brotli/Gzip compression) with ~600 KB of below-the-fold assets. If incomplete scrolls, early navigations, and request deduplication prevent fetching just **300 KB per visit on average** (e.g., 5 unviewed WebP images at ~45 KB each + 1 deferred or deduplicated gzipped script at ~75 KB):
|
|
33
|
+
|
|
34
|
+
* **109.5 Terabytes** of unnecessary network traffic saved per year.
|
|
35
|
+
* **17,558 kWh of electricity** saved (enough to power an average residential apartment for **~7.5 years**).
|
|
36
|
+
* **7,741 kg of CO₂ emissions** prevented (equivalent to the annual carbon offset of **~350 mature trees**).
|
|
37
|
+
* **Lower Main Thread Execution Cost:** Deferring or deduplicating a single 75 KB gzipped script avoids parsing and compiling ~250–300 KB of raw JavaScript in V8, preserving mobile battery life and **INP** responsiveness.
|
|
38
|
+
|
|
39
|
+
## Installation
|
|
40
|
+
|
|
41
|
+
### Via NPM / Yarn
|
|
42
|
+
|
|
43
|
+
```bash
|
|
44
|
+
npm install @quiql/lazy
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
```javascript
|
|
48
|
+
// ES Modules
|
|
49
|
+
import QuiqlLazy from '@quiql/lazy';
|
|
50
|
+
|
|
51
|
+
// CommonJS
|
|
52
|
+
const QuiqlLazy = require('@quiql/lazy');
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
### Via `<script>` tag (or CDN)
|
|
56
|
+
```html
|
|
57
|
+
<!-- Local file -->
|
|
58
|
+
<script src="path/to/quiql-lazy.min.js"></script>
|
|
59
|
+
|
|
60
|
+
<!-- Or via jsDelivr CDN -->
|
|
61
|
+
<script src="https://cdn.jsdelivr.net/npm/@quiql/lazy@1.0.0/dist/quiql-lazy.min.js"></script>
|
|
62
|
+
|
|
63
|
+
<script>
|
|
64
|
+
// Available globally as window.QuiqlLazy
|
|
65
|
+
</script>
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
## Demo
|
|
69
|
+
|
|
70
|
+
Check out the [`demo/`](https://github.com/quiql/lazy/tree/main/demo) directory for complete working examples:
|
|
71
|
+
* [`demo/index.html`](https://github.com/quiql/lazy/blob/main/demo/index.html) — HTML markup examples for lazy images, responsive `srcset`, background images, and custom trigger blocks.
|
|
72
|
+
* [`demo/style.css`](https://github.com/quiql/lazy/blob/main/demo/style.css) — CSS transitions and visual state styles (`.lazy`, `.loading`, `.loaded`, `.error`).
|
|
73
|
+
* [`demo/script.js`](https://github.com/quiql/lazy/blob/main/demo/script.js) — JavaScript initialization examples for `LazyLoad`, `CustomLoad`, and dynamic resource loading.
|
|
74
|
+
|
|
75
|
+
## Quick Start
|
|
76
|
+
|
|
77
|
+
### 1. Lazy Loading Media (`QuiqlLazy.LazyLoad`)
|
|
78
|
+
|
|
79
|
+
Add the `lazy` class and `data-src` (or `data-bg`) attribute to your elements:
|
|
80
|
+
|
|
81
|
+
```html
|
|
82
|
+
<!-- Standard image -->
|
|
83
|
+
<img class="lazy" data-src="image.jpg" alt="Lazy image" />
|
|
84
|
+
|
|
85
|
+
<!-- With inline placeholder (optional, for strict W3C validation & search bots;
|
|
86
|
+
avoids extra HTTP requests) -->
|
|
87
|
+
<img
|
|
88
|
+
class="lazy"
|
|
89
|
+
src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"
|
|
90
|
+
data-src="image.jpg"
|
|
91
|
+
width="800"
|
|
92
|
+
height="600"
|
|
93
|
+
alt="Lazy image"
|
|
94
|
+
/>
|
|
95
|
+
|
|
96
|
+
<!-- Responsive image -->
|
|
97
|
+
<img
|
|
98
|
+
class="lazy"
|
|
99
|
+
data-src="image-800.jpg"
|
|
100
|
+
data-srcset="image-400.jpg 400w, image-800.jpg 800w"
|
|
101
|
+
sizes="(max-width: 600px) 400px, 800px"
|
|
102
|
+
alt="Responsive lazy image"
|
|
103
|
+
/>
|
|
104
|
+
|
|
105
|
+
<!-- Background image -->
|
|
106
|
+
<div class="lazy" data-bg="hero-background.jpg"></div>
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
Initialize `LazyLoad` in your JavaScript:
|
|
110
|
+
|
|
111
|
+
```javascript
|
|
112
|
+
const lazyMedia = new QuiqlLazy.LazyLoad({
|
|
113
|
+
options: {
|
|
114
|
+
rootMargin: '200px 0px',
|
|
115
|
+
threshold: 0
|
|
116
|
+
},
|
|
117
|
+
onLoad: (target) => {
|
|
118
|
+
console.log('Loaded:', target);
|
|
119
|
+
},
|
|
120
|
+
onError: (target) => {
|
|
121
|
+
console.error('Failed to load:', target);
|
|
122
|
+
}
|
|
123
|
+
});
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
### 2. Custom Viewport Triggers (`QuiqlLazy.CustomLoad`)
|
|
127
|
+
|
|
128
|
+
Trigger any custom JavaScript function when specific elements appear in the viewport. For UI widgets like sliders, loading CSS before JS ensures styles are applied before layout calculations run:
|
|
129
|
+
|
|
130
|
+
```javascript
|
|
131
|
+
const sliders = document.querySelectorAll('.swiper');
|
|
132
|
+
|
|
133
|
+
if (sliders.length) {
|
|
134
|
+
const loadSwiper = async () => {
|
|
135
|
+
// Load CSS first so layout styles are ready before JS initializes
|
|
136
|
+
await QuiqlLazy.loadStyle('/css/swiper-bundle.min.css', () => {
|
|
137
|
+
console.log('Swiper CSS loaded!');
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
await QuiqlLazy.loadScript('/js/swiper-bundle.min.js', () => {
|
|
141
|
+
console.log('Swiper JS loaded!');
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
new Swiper('.swiper', {
|
|
145
|
+
loop: true,
|
|
146
|
+
pagination: { el: '.swiper-pagination' }
|
|
147
|
+
});
|
|
148
|
+
};
|
|
149
|
+
|
|
150
|
+
new QuiqlLazy.CustomLoad({
|
|
151
|
+
targets: sliders,
|
|
152
|
+
options: {
|
|
153
|
+
rootMargin: '30%',
|
|
154
|
+
threshold: 0
|
|
155
|
+
},
|
|
156
|
+
load: loadSwiper
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
### 3. Dynamic Resource Loading
|
|
162
|
+
|
|
163
|
+
Load scripts, stylesheets, or custom HTML elements on demand:
|
|
164
|
+
|
|
165
|
+
```javascript
|
|
166
|
+
// Load a script (async by default)
|
|
167
|
+
await QuiqlLazy.loadScript('/js/analytics.js', (event) => {
|
|
168
|
+
console.log('Analytics script loaded');
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
// Load a stylesheet
|
|
172
|
+
await QuiqlLazy.loadStyle('/css/theme.css');
|
|
173
|
+
|
|
174
|
+
// Load any custom tag with attributes
|
|
175
|
+
await QuiqlLazy.loadResource('script', {
|
|
176
|
+
src: '/js/app.js',
|
|
177
|
+
type: 'module',
|
|
178
|
+
defer: true,
|
|
179
|
+
'data-user-id': '12345'
|
|
180
|
+
});
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
## API Reference & Parameters
|
|
184
|
+
|
|
185
|
+
### Global Configuration (`QuiqlLazy.config`)
|
|
186
|
+
|
|
187
|
+
You can modify global behavior before calling resource loading methods:
|
|
188
|
+
|
|
189
|
+
```javascript
|
|
190
|
+
QuiqlLazy.config = {
|
|
191
|
+
shouldRunIfLoaded: true,
|
|
192
|
+
scanExistingResources: false,
|
|
193
|
+
ignoreOnScan: [],
|
|
194
|
+
debug: false
|
|
195
|
+
};
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
| Parameter | Type | Default | Description |
|
|
199
|
+
| :--- | :--- | :--- | :--- |
|
|
200
|
+
| `shouldRunIfLoaded` | `boolean` | `true` | If `true`, executes the `onload` callback even if the resource was already cached/loaded earlier. |
|
|
201
|
+
| `scanExistingResources` | `boolean` | `false` | Scans existing `<script[src]>` and `<link[rel="stylesheet"]>` in the DOM on the first load call to prevent duplicate loading. |
|
|
202
|
+
| `ignoreOnScan` | `string[]` | `[]` | Array of URL substrings to exclude when `scanExistingResources` is enabled (e.g., `['gtm.js', 'analytics']`). |
|
|
203
|
+
| `debug` | `boolean` | `false` | Enables console warnings and logs for debugging. |
|
|
204
|
+
|
|
205
|
+
---
|
|
206
|
+
|
|
207
|
+
### `QuiqlLazy.LazyLoad` Options
|
|
208
|
+
|
|
209
|
+
Pass a settings object to `new QuiqlLazy.LazyLoad(settings)`:
|
|
210
|
+
|
|
211
|
+
| Parameter | Type | Default | Description |
|
|
212
|
+
| :--- | :--- | :--- | :--- |
|
|
213
|
+
| `targets` | `Element \| NodeList \| Array \| Iterable` | `null` | Specific elements to observe. If omitted, automatically queries `.lazy[data-src], .lazy[data-bg]`. |
|
|
214
|
+
| `options` | `IntersectionObserverInit` | `{ root: null, rootMargin: '200px 0px', threshold: 0 }` | Native `IntersectionObserver` options. |
|
|
215
|
+
| `attributes` | `object` | `{ src: 'data-src', srcset: 'data-srcset', bg: 'data-bg' }` | Custom data attributes used to store source URLs. |
|
|
216
|
+
| `classes` | `object` | `{ lazy: 'lazy', loading: 'loading', loaded: 'loaded', error: 'error' }` | CSS classes applied during element lifecycle states. |
|
|
217
|
+
| `onLoad` | `(target: Element) => void` | `undefined` | Callback fired when an image or background finishes loading. |
|
|
218
|
+
| `onError` | `(target: Element) => void` | `undefined` | Callback fired when an image or background fails to load. |
|
|
219
|
+
| `callback` | `(entries, observer) => void` | `undefined` | Overrides the default internal intersection handler completely. |
|
|
220
|
+
|
|
221
|
+
---
|
|
222
|
+
|
|
223
|
+
### `QuiqlLazy.CustomLoad` Options
|
|
224
|
+
|
|
225
|
+
Pass a settings object to `new QuiqlLazy.CustomLoad(settings)`:
|
|
226
|
+
|
|
227
|
+
| Parameter | Type | Default | Description |
|
|
228
|
+
| :--- | :--- | :--- | :--- |
|
|
229
|
+
| `targets` | `Element \| NodeList \| Array \| Iterable` | `null` | **Required.** Elements that trigger the `load` function upon entering the viewport. |
|
|
230
|
+
| `load` | `() => void` | `null` | Function executed once when any of the `targets` intersects the viewport. |
|
|
231
|
+
| `options` | `IntersectionObserverInit` | `{ root: null, rootMargin: '200px 0px', threshold: 0 }` | Native `IntersectionObserver` options. |
|
|
232
|
+
| `callback` | `(entries, observer) => void` | `undefined` | Overrides the default `onAny` intersection handler. |
|
|
233
|
+
|
|
234
|
+
---
|
|
235
|
+
|
|
236
|
+
### Observer Instance Methods
|
|
237
|
+
|
|
238
|
+
Both `LazyLoad` and `CustomLoad` inherit from `QuiqlLazy.Observer` and share these methods:
|
|
239
|
+
|
|
240
|
+
* **`instance.add(targets)`**: Starts observing new elements (useful after dynamically adding content via AJAX/fetch). If called without arguments on `LazyLoad`, re-scans the DOM for `.lazy` elements.
|
|
241
|
+
* **`instance.remove(targets)`**: Stops observing specific elements.
|
|
242
|
+
* **`instance.clear()`**: Disconnects the observer and stops watching all elements.
|
|
243
|
+
|
|
244
|
+
---
|
|
245
|
+
|
|
246
|
+
### Static Methods & Helpers
|
|
247
|
+
|
|
248
|
+
* **`QuiqlLazy.loadResource(tag, attrs, options)`**: Core method for creating and injecting a DOM resource. Returns a `Promise<HTMLElement | null>`. `options` accepts temporary overrides for `QuiqlLazy.config`.
|
|
249
|
+
* **`QuiqlLazy.loadScript(url, onload, options)`**: Shortcut for `loadResource('script', { src: url, async: true, onload }, options)`.
|
|
250
|
+
* **`QuiqlLazy.loadStyle(url, onload, options)`**: Shortcut for `loadResource('link', { href: url, rel: 'stylesheet', onload }, options)`.
|
|
251
|
+
* **`QuiqlLazy.normalizeUrl(url)`**: Resolves a relative URL against `window.location.href` into a full normalized URL.
|
|
252
|
+
* **`QuiqlLazy.onEach(action, shouldUnobserve = true)`**: Helper for custom `IntersectionObserver` callbacks. Runs `action(entry, observer, entries)` for every intersecting element and unobserves it by default.
|
|
253
|
+
* **`QuiqlLazy.onAny(action, shouldDisconnect = true)`**: Helper for custom `IntersectionObserver` callbacks. Runs `action(entry, observer, entries)` on the first intersecting element and disconnects the observer by default.
|
|
254
|
+
|
|
255
|
+
## Advanced Recipes
|
|
256
|
+
|
|
257
|
+
### Loading Resources with Automatic Retries
|
|
258
|
+
|
|
259
|
+
To keep the core library minimal and lightweight, automatic network retry logic is not built in. Because `QuiqlLazy` automatically removes failed resources from its cache, you can easily wrap `loadScript` or `loadResource` in a retry helper:
|
|
260
|
+
|
|
261
|
+
```javascript
|
|
262
|
+
async function loadWithRetry(url, retries = 3, delay = 1000) {
|
|
263
|
+
try {
|
|
264
|
+
return await QuiqlLazy.loadScript(url);
|
|
265
|
+
} catch (error) {
|
|
266
|
+
if (retries <= 0) {
|
|
267
|
+
throw error;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
271
|
+
|
|
272
|
+
return loadWithRetry(url, retries - 1, delay);
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
// Usage example:
|
|
277
|
+
(async () => {
|
|
278
|
+
try {
|
|
279
|
+
const script = await loadWithRetry('https://example.com/widget.js', 3, 1000);
|
|
280
|
+
console.log('Script loaded successfully:', script);
|
|
281
|
+
} catch (error) {
|
|
282
|
+
console.error('Failed to load script after multiple attempts:', error);
|
|
283
|
+
}
|
|
284
|
+
})();
|
|
285
|
+
```
|
|
286
|
+
|
|
287
|
+
### Native Browser `loading="lazy"` with Fallback
|
|
288
|
+
|
|
289
|
+
To keep the core focused on `IntersectionObserver` and resource loading, native `loading="lazy"` handling is not included by default. If you prefer native browser lazy loading for `<img>` elements with an automatic fallback to `QuiqlLazy.LazyLoad` for older browsers, you can add this helper:
|
|
290
|
+
|
|
291
|
+
```javascript
|
|
292
|
+
function initNativeLazy(targets = '.lazy[data-src]') {
|
|
293
|
+
if (typeof window === 'undefined') return;
|
|
294
|
+
|
|
295
|
+
const elements = typeof targets === 'string'
|
|
296
|
+
? document.querySelectorAll(targets)
|
|
297
|
+
: targets instanceof Element ? [targets] : Array.from(targets || []);
|
|
298
|
+
|
|
299
|
+
// Fallback to QuiqlLazy.LazyLoad if native lazy loading is not supported
|
|
300
|
+
if (!('loading' in HTMLImageElement.prototype)) {
|
|
301
|
+
return new QuiqlLazy.LazyLoad({ targets: elements });
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
const { classes, attributes } = QuiqlLazy.Observer.lazyDefaults;
|
|
305
|
+
|
|
306
|
+
const onFinish = (event) => {
|
|
307
|
+
const el = event.currentTarget;
|
|
308
|
+
|
|
309
|
+
el.removeEventListener('load', onFinish);
|
|
310
|
+
el.removeEventListener('error', onFinish);
|
|
311
|
+
el.classList.replace(
|
|
312
|
+
classes.loading,
|
|
313
|
+
event.type === 'load' ? classes.loaded : classes.error
|
|
314
|
+
);
|
|
315
|
+
};
|
|
316
|
+
|
|
317
|
+
for (const el of elements) {
|
|
318
|
+
if (!(el instanceof HTMLImageElement)) continue;
|
|
319
|
+
|
|
320
|
+
el.classList.replace(classes.lazy, classes.loading);
|
|
321
|
+
|
|
322
|
+
el.addEventListener('load', onFinish);
|
|
323
|
+
el.addEventListener('error', onFinish);
|
|
324
|
+
|
|
325
|
+
el.loading = 'lazy';
|
|
326
|
+
|
|
327
|
+
const srcset = el.getAttribute(attributes.srcset);
|
|
328
|
+
if (srcset) {
|
|
329
|
+
el.srcset = srcset;
|
|
330
|
+
el.removeAttribute(attributes.srcset);
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
const src = el.getAttribute(attributes.src);
|
|
334
|
+
if (src) {
|
|
335
|
+
el.src = src;
|
|
336
|
+
el.removeAttribute(attributes.src);
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
// Usage example:
|
|
342
|
+
initNativeLazy('.lazy[data-src]');
|
|
343
|
+
```
|
|
344
|
+
|
|
345
|
+
---
|
|
346
|
+
|
|
347
|
+
🧬 **Quiql Ecosystem 2026** — *Quick eQuals Quality*
|
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
export interface QuiqlLazyConfig {
|
|
2
|
+
/** Execute the `onload` callback even if the resource was already cached/loaded earlier. @default true */
|
|
3
|
+
shouldRunIfLoaded: boolean;
|
|
4
|
+
/** Scan existing `<script[src]>` and `<link[rel="stylesheet"]>` in the DOM on the first load call to prevent duplicate loading. @default false */
|
|
5
|
+
scanExistingResources: boolean;
|
|
6
|
+
/** Array of URL substrings to exclude when `scanExistingResources` is enabled (e.g. `['gtm.js', 'analytics']`). @default [] */
|
|
7
|
+
ignoreOnScan: string[];
|
|
8
|
+
/** Enable console warnings and logs for debugging. @default false */
|
|
9
|
+
debug: boolean;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export type QuiqlLazyLoadOptions = Partial<QuiqlLazyConfig>;
|
|
13
|
+
|
|
14
|
+
export interface QuiqlLazyResourceAttrs {
|
|
15
|
+
src?: string;
|
|
16
|
+
href?: string;
|
|
17
|
+
onload?: (event: Event | null) => void;
|
|
18
|
+
onerror?: (event: Event | Error | null) => void;
|
|
19
|
+
[key: string]: string | number | boolean | ((event: any) => void) | undefined | null;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export type QuiqlLazyTargets =
|
|
23
|
+
| Element
|
|
24
|
+
| NodeListOf<Element>
|
|
25
|
+
| HTMLCollectionOf<Element>
|
|
26
|
+
| Iterable<Element>
|
|
27
|
+
| Element[]
|
|
28
|
+
| null
|
|
29
|
+
| undefined;
|
|
30
|
+
|
|
31
|
+
export type QuiqlLazyIntersectionCallback = (
|
|
32
|
+
entries: IntersectionObserverEntry[],
|
|
33
|
+
observer: IntersectionObserver
|
|
34
|
+
) => void;
|
|
35
|
+
|
|
36
|
+
export type QuiqlLazyActionCallback = (
|
|
37
|
+
entry: IntersectionObserverEntry,
|
|
38
|
+
observer: IntersectionObserver,
|
|
39
|
+
entries: IntersectionObserverEntry[]
|
|
40
|
+
) => void;
|
|
41
|
+
|
|
42
|
+
export interface QuiqlLazyProcessOptions {
|
|
43
|
+
shouldUnobserve?: boolean;
|
|
44
|
+
shouldDisconnect?: boolean;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export interface QuiqlLazyMediaAttributes {
|
|
48
|
+
/** @default 'data-src' */
|
|
49
|
+
src?: string;
|
|
50
|
+
/** @default 'data-srcset' */
|
|
51
|
+
srcset?: string;
|
|
52
|
+
/** @default 'data-bg' */
|
|
53
|
+
bg?: string;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export interface QuiqlLazyMediaClasses {
|
|
57
|
+
/** @default 'lazy' */
|
|
58
|
+
lazy?: string;
|
|
59
|
+
/** @default 'loading' */
|
|
60
|
+
loading?: string;
|
|
61
|
+
/** @default 'loaded' */
|
|
62
|
+
loaded?: string;
|
|
63
|
+
/** @default 'error' */
|
|
64
|
+
error?: string;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export interface QuiqlLazyObserverSettings {
|
|
68
|
+
/** Native `IntersectionObserver` options. @default { root: null, rootMargin: '200px 0px', threshold: 0 } */
|
|
69
|
+
options?: IntersectionObserverInit;
|
|
70
|
+
/** Specific elements to observe. */
|
|
71
|
+
targets?: QuiqlLazyTargets;
|
|
72
|
+
/** Custom intersection handler that overrides the default internal callback. */
|
|
73
|
+
callback?: QuiqlLazyIntersectionCallback;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export interface QuiqlLazyMediaSettings extends QuiqlLazyObserverSettings {
|
|
77
|
+
/** Custom data attributes used to store source URLs. */
|
|
78
|
+
attributes?: QuiqlLazyMediaAttributes;
|
|
79
|
+
/** CSS classes applied during element lifecycle states. */
|
|
80
|
+
classes?: QuiqlLazyMediaClasses;
|
|
81
|
+
/** Callback fired when an image or background finishes loading. */
|
|
82
|
+
onLoad?: (target: Element) => void;
|
|
83
|
+
/** Callback fired when an image or background fails to load. */
|
|
84
|
+
onError?: (target: Element) => void;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export interface QuiqlLazyCustomSettings extends QuiqlLazyObserverSettings {
|
|
88
|
+
/** Function executed once when any of the `targets` intersects the viewport. */
|
|
89
|
+
load?: () => void;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export interface QuiqlLazyMediaResolvedConfig {
|
|
93
|
+
options: IntersectionObserverInit;
|
|
94
|
+
attributes: Required<QuiqlLazyMediaAttributes>;
|
|
95
|
+
classes: Required<QuiqlLazyMediaClasses>;
|
|
96
|
+
debug: boolean;
|
|
97
|
+
onLoad?: (target: Element) => void;
|
|
98
|
+
onError?: (target: Element) => void;
|
|
99
|
+
targets?: QuiqlLazyTargets;
|
|
100
|
+
callback?: QuiqlLazyIntersectionCallback;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
declare class QuiqlLazyObserver {
|
|
104
|
+
static defaults: {
|
|
105
|
+
options: IntersectionObserverInit;
|
|
106
|
+
};
|
|
107
|
+
|
|
108
|
+
static lazyDefaults: {
|
|
109
|
+
attributes: Required<QuiqlLazyMediaAttributes>;
|
|
110
|
+
classes: Required<QuiqlLazyMediaClasses>;
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
constructor(settings?: QuiqlLazyObserverSettings & Record<string, any>);
|
|
114
|
+
|
|
115
|
+
/** Starts observing new elements. If called without arguments on `LazyLoad`, re-scans the DOM for `.lazy` elements. */
|
|
116
|
+
add(targets?: QuiqlLazyTargets): void;
|
|
117
|
+
/** Stops observing specific elements. */
|
|
118
|
+
remove(targets: QuiqlLazyTargets): void;
|
|
119
|
+
/** Disconnects the observer and stops watching all elements. */
|
|
120
|
+
clear(): void;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
declare class QuiqlLazyLoad extends QuiqlLazyObserver {
|
|
124
|
+
constructor(settings?: QuiqlLazyMediaSettings);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
declare class QuiqlLazyCustomLoad extends QuiqlLazyObserver {
|
|
128
|
+
constructor(settings?: QuiqlLazyCustomSettings);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
declare class QuiqlLazy {
|
|
132
|
+
/** Global library configuration. */
|
|
133
|
+
static config: QuiqlLazyConfig;
|
|
134
|
+
|
|
135
|
+
/** Resolves a relative URL against `window.location.href` into a full normalized URL. */
|
|
136
|
+
static normalizeUrl(url: string): string;
|
|
137
|
+
|
|
138
|
+
/** Core method for creating, caching, and injecting a DOM resource. */
|
|
139
|
+
static loadResource<T extends keyof HTMLElementTagNameMap>(
|
|
140
|
+
tag: T,
|
|
141
|
+
attrs: QuiqlLazyResourceAttrs,
|
|
142
|
+
options?: QuiqlLazyLoadOptions
|
|
143
|
+
): Promise<HTMLElementTagNameMap[T] | null>;
|
|
144
|
+
static loadResource(
|
|
145
|
+
tag: string,
|
|
146
|
+
attrs: QuiqlLazyResourceAttrs,
|
|
147
|
+
options?: QuiqlLazyLoadOptions
|
|
148
|
+
): Promise<HTMLElement | null>;
|
|
149
|
+
|
|
150
|
+
/** Dynamically loads an external `<script>` (async by default) with request deduplication. */
|
|
151
|
+
static loadScript(
|
|
152
|
+
url: string,
|
|
153
|
+
onload?: (event: Event | null) => void,
|
|
154
|
+
options?: QuiqlLazyLoadOptions
|
|
155
|
+
): Promise<HTMLScriptElement | null>;
|
|
156
|
+
|
|
157
|
+
/** Dynamically loads an external stylesheet (`<link rel="stylesheet">`) with request deduplication. */
|
|
158
|
+
static loadStyle(
|
|
159
|
+
url: string,
|
|
160
|
+
onload?: (event: Event | null) => void,
|
|
161
|
+
options?: QuiqlLazyLoadOptions
|
|
162
|
+
): Promise<HTMLLinkElement | null>;
|
|
163
|
+
|
|
164
|
+
static Observer: typeof QuiqlLazyObserver;
|
|
165
|
+
/** Lazy loader for `<img>` (`src`, `srcset`, `sizes`) and background images (`data-bg`). */
|
|
166
|
+
static LazyLoad: typeof QuiqlLazyLoad;
|
|
167
|
+
/** Viewport trigger for executing custom logic (widgets, scripts, analytics) on intersection. */
|
|
168
|
+
static CustomLoad: typeof QuiqlLazyCustomLoad;
|
|
169
|
+
|
|
170
|
+
static mediaCallback(
|
|
171
|
+
config: QuiqlLazyMediaResolvedConfig
|
|
172
|
+
): (entry: IntersectionObserverEntry) => Promise<void>;
|
|
173
|
+
|
|
174
|
+
static customCallback(load?: (() => void) | null): () => void;
|
|
175
|
+
|
|
176
|
+
static processIntersection(
|
|
177
|
+
action: QuiqlLazyActionCallback,
|
|
178
|
+
options?: QuiqlLazyProcessOptions
|
|
179
|
+
): QuiqlLazyIntersectionCallback;
|
|
180
|
+
|
|
181
|
+
/** Helper for custom `IntersectionObserver` callbacks. Runs `action` for every intersecting element and unobserves it by default. */
|
|
182
|
+
static onEach(
|
|
183
|
+
action: QuiqlLazyActionCallback,
|
|
184
|
+
shouldUnobserve?: boolean
|
|
185
|
+
): QuiqlLazyIntersectionCallback;
|
|
186
|
+
|
|
187
|
+
/** Helper for custom `IntersectionObserver` callbacks. Runs `action` on the first intersecting element and disconnects by default. */
|
|
188
|
+
static onAny(
|
|
189
|
+
action: QuiqlLazyActionCallback,
|
|
190
|
+
shouldDisconnect?: boolean
|
|
191
|
+
): QuiqlLazyIntersectionCallback;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
declare global {
|
|
195
|
+
interface Window {
|
|
196
|
+
QuiqlLazy: typeof QuiqlLazy;
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
export = QuiqlLazy;
|
|
@@ -0,0 +1,528 @@
|
|
|
1
|
+
(() => {
|
|
2
|
+
const isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined';
|
|
3
|
+
const isFunction = (val) => typeof val === 'function';
|
|
4
|
+
const executeCallback = (callback, argument) => {
|
|
5
|
+
if (isFunction(callback)) {
|
|
6
|
+
try {
|
|
7
|
+
callback(argument);
|
|
8
|
+
} catch(error) {
|
|
9
|
+
console.error(error);
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
const normalizeTargets = (targets) => {
|
|
14
|
+
if (!targets) {
|
|
15
|
+
return [];
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
if (targets instanceof Element) {
|
|
19
|
+
return [targets];
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
if (typeof targets !== 'string' && typeof targets[Symbol.iterator] === 'function') {
|
|
23
|
+
return Array.from(targets);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
return [];
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
class QuiqlLazy {
|
|
30
|
+
static config = {
|
|
31
|
+
shouldRunIfLoaded: true,
|
|
32
|
+
scanExistingResources: false,
|
|
33
|
+
ignoreOnScan: [],
|
|
34
|
+
debug: false
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
static #areResourcesScanned = false;
|
|
38
|
+
|
|
39
|
+
static #loadedResources = new Map();
|
|
40
|
+
|
|
41
|
+
static normalizeUrl(url) {
|
|
42
|
+
try {
|
|
43
|
+
return new URL(url, window.location.href).href;
|
|
44
|
+
} catch(error) {
|
|
45
|
+
if (this.config?.debug) {
|
|
46
|
+
console.warn(`QuiqlLazy: Failed to normalize URL "${url}"`, error);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
return url;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
static #createRecord(element, status = 'loaded') {
|
|
54
|
+
return {
|
|
55
|
+
element,
|
|
56
|
+
status,
|
|
57
|
+
loadEvent: null,
|
|
58
|
+
errorEvent: null,
|
|
59
|
+
onloads: new Set(),
|
|
60
|
+
onerrors: new Set()
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
static #checkExistingResources() {
|
|
65
|
+
const ignoreList = Array.isArray(this.config?.ignoreOnScan) ? this.config.ignoreOnScan : [];
|
|
66
|
+
const isIgnored = (url) => ignoreList.some(pattern => url.includes(pattern));
|
|
67
|
+
|
|
68
|
+
const selectors = [
|
|
69
|
+
{ sel: 'script[src]', attr: 'src' },
|
|
70
|
+
{ sel: 'link[rel="stylesheet"][href]', attr: 'href' }
|
|
71
|
+
];
|
|
72
|
+
|
|
73
|
+
selectors.forEach(({ sel, attr }) => {
|
|
74
|
+
document.querySelectorAll(sel).forEach(element => {
|
|
75
|
+
const rawUrl = element[attr];
|
|
76
|
+
|
|
77
|
+
if (!rawUrl) return;
|
|
78
|
+
|
|
79
|
+
const url = this.normalizeUrl(rawUrl);
|
|
80
|
+
|
|
81
|
+
if (!isIgnored(url) && !this.#loadedResources.has(url)) {
|
|
82
|
+
this.#loadedResources.set(url, this.#createRecord(element));
|
|
83
|
+
}
|
|
84
|
+
});
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
if (this.config.debug) {
|
|
88
|
+
console.log(`QuiqlLazy: Scanned existing resources. Total in cache: ${this.#loadedResources.size}`);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
static #handleResourceResult(record, element, url, status, recordProp, callbackKey, event) {
|
|
93
|
+
record.status = status;
|
|
94
|
+
record[recordProp] = event;
|
|
95
|
+
|
|
96
|
+
record[callbackKey].forEach(callback => {
|
|
97
|
+
try {
|
|
98
|
+
callback(event);
|
|
99
|
+
} catch(error) {
|
|
100
|
+
console.error('QuiqlLazy: Error in user callback', error);
|
|
101
|
+
}
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
record.onloads.clear();
|
|
105
|
+
record.onerrors.clear();
|
|
106
|
+
|
|
107
|
+
element.onload = null;
|
|
108
|
+
element.onerror = null;
|
|
109
|
+
|
|
110
|
+
if (status === 'error') {
|
|
111
|
+
this.#loadedResources.delete(url);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
static async loadResource(tag, attrs, options = {}) {
|
|
116
|
+
if (!isBrowser) return null;
|
|
117
|
+
|
|
118
|
+
const currentConfig = { ...this.config, ...options };
|
|
119
|
+
const { src, href, onload, onerror, ...restAttrs } = attrs;
|
|
120
|
+
const urlAttr = src ? 'src' : 'href';
|
|
121
|
+
let url = src || href;
|
|
122
|
+
|
|
123
|
+
if (currentConfig.scanExistingResources && !this.#areResourcesScanned) {
|
|
124
|
+
this.#areResourcesScanned = true;
|
|
125
|
+
this.#checkExistingResources();
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
if (!url || typeof url !== 'string') {
|
|
129
|
+
if (currentConfig.debug) {
|
|
130
|
+
console.warn('QuiqlLazy: url is not passed!');
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
return null;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
url = this.normalizeUrl(url);
|
|
137
|
+
|
|
138
|
+
if (this.#loadedResources.has(url)) {
|
|
139
|
+
const record = this.#loadedResources.get(url);
|
|
140
|
+
|
|
141
|
+
if (record.status === 'loaded') {
|
|
142
|
+
if (currentConfig.shouldRunIfLoaded) {
|
|
143
|
+
executeCallback(onload, record.loadEvent);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
return record.element;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
if (record.status === 'error') {
|
|
150
|
+
executeCallback(onerror, record.errorEvent);
|
|
151
|
+
|
|
152
|
+
throw record.errorEvent || new Error(`QuiqlLazy: Failed to load resource: ${url}`);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// record.status === 'pending'
|
|
156
|
+
return new Promise((resolve, reject) => {
|
|
157
|
+
record.onloads.add((event) => {
|
|
158
|
+
executeCallback(onload, event);
|
|
159
|
+
|
|
160
|
+
resolve(record.element);
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
record.onerrors.add((event) => {
|
|
164
|
+
executeCallback(onerror, event);
|
|
165
|
+
|
|
166
|
+
reject(event);
|
|
167
|
+
});
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
return new Promise((resolve, reject) => {
|
|
172
|
+
const element = document.createElement(tag);
|
|
173
|
+
const record = this.#createRecord(element, 'pending');
|
|
174
|
+
|
|
175
|
+
if (isFunction(onload)) {
|
|
176
|
+
record.onloads.add(onload);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
if (isFunction(onerror)) {
|
|
180
|
+
record.onerrors.add(onerror);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
this.#loadedResources.set(url, record);
|
|
184
|
+
|
|
185
|
+
element.onload = (event) => {
|
|
186
|
+
this.#handleResourceResult(record, element, url, 'loaded', 'loadEvent', 'onloads', event);
|
|
187
|
+
|
|
188
|
+
resolve(element);
|
|
189
|
+
};
|
|
190
|
+
|
|
191
|
+
element.onerror = (event) => {
|
|
192
|
+
if (currentConfig.debug) {
|
|
193
|
+
console.error(`QuiqlLazy: Failed to load resource "${url}"`);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
if (element.parentNode) {
|
|
197
|
+
element.parentNode.removeChild(element);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
this.#handleResourceResult(record, element, url, 'error', 'errorEvent', 'onerrors', event);
|
|
201
|
+
|
|
202
|
+
reject(event);
|
|
203
|
+
};
|
|
204
|
+
|
|
205
|
+
for (const key in restAttrs) {
|
|
206
|
+
const val = restAttrs[key];
|
|
207
|
+
|
|
208
|
+
if (val != null && val !== false) {
|
|
209
|
+
element.setAttribute(key, val === true ? '' : String(val));
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
element[urlAttr] = url;
|
|
214
|
+
|
|
215
|
+
const target = tag === 'link' ? document.head : document.body;
|
|
216
|
+
target.appendChild(element);
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
static loadScript(url, onload = undefined, options = {}) {
|
|
221
|
+
return this.loadResource('script', {
|
|
222
|
+
src: url,
|
|
223
|
+
async: true,
|
|
224
|
+
onload
|
|
225
|
+
}, options);
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
static loadStyle(url, onload = undefined, options = {}) {
|
|
229
|
+
return this.loadResource('link', {
|
|
230
|
+
href: url,
|
|
231
|
+
rel: 'stylesheet',
|
|
232
|
+
onload
|
|
233
|
+
}, options);
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
static Observer = class {
|
|
237
|
+
#instance = null;
|
|
238
|
+
#isRealObserver = true;
|
|
239
|
+
#config = {};
|
|
240
|
+
|
|
241
|
+
static defaults = {
|
|
242
|
+
options: {
|
|
243
|
+
root: null,
|
|
244
|
+
rootMargin: '200px 0px',
|
|
245
|
+
threshold: 0,
|
|
246
|
+
}
|
|
247
|
+
};
|
|
248
|
+
|
|
249
|
+
static lazyDefaults = {
|
|
250
|
+
attributes: {
|
|
251
|
+
src: 'data-src',
|
|
252
|
+
srcset: 'data-srcset',
|
|
253
|
+
bg: 'data-bg',
|
|
254
|
+
},
|
|
255
|
+
classes: {
|
|
256
|
+
lazy: 'lazy',
|
|
257
|
+
loading: 'loading',
|
|
258
|
+
loaded: 'loaded',
|
|
259
|
+
error: 'error',
|
|
260
|
+
}
|
|
261
|
+
};
|
|
262
|
+
|
|
263
|
+
constructor(settings = {}) {
|
|
264
|
+
if (!isBrowser) {
|
|
265
|
+
console.warn('QuiqlLazy: Work is only possible in a browser');
|
|
266
|
+
|
|
267
|
+
return;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
const core = QuiqlLazy;
|
|
271
|
+
|
|
272
|
+
const defaults = this.constructor.defaults;
|
|
273
|
+
const lazyDefaults = this.constructor.lazyDefaults;
|
|
274
|
+
|
|
275
|
+
this.#config = {
|
|
276
|
+
...defaults,
|
|
277
|
+
...settings,
|
|
278
|
+
options: { ...defaults.options, ...settings.options },
|
|
279
|
+
debug: core.config.debug
|
|
280
|
+
};
|
|
281
|
+
|
|
282
|
+
const config = this.#config;
|
|
283
|
+
|
|
284
|
+
if (config.type === 'media') {
|
|
285
|
+
for (const key of ['attributes', 'classes']) {
|
|
286
|
+
config[key] = { ...lazyDefaults[key], ...settings[key] };
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
if (!isFunction(config.callback)) {
|
|
291
|
+
if (config.type === 'media') {
|
|
292
|
+
config.callback = core.onEach(core.mediaCallback(config));
|
|
293
|
+
} else {
|
|
294
|
+
config.callback = core.onAny(core.customCallback(config.load));
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
this.#init();
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
#init() {
|
|
302
|
+
const { options, debug, type, targets, callback } = this.#config;
|
|
303
|
+
|
|
304
|
+
const isSupportedIntersectionObserver = isBrowser &&
|
|
305
|
+
'IntersectionObserver' in window &&
|
|
306
|
+
'IntersectionObserverEntry' in window &&
|
|
307
|
+
'isIntersecting' in window.IntersectionObserverEntry.prototype;
|
|
308
|
+
|
|
309
|
+
if (isSupportedIntersectionObserver) {
|
|
310
|
+
this.#instance = new IntersectionObserver(callback, options);
|
|
311
|
+
} else {
|
|
312
|
+
this.#isRealObserver = false;
|
|
313
|
+
this.#instance = {
|
|
314
|
+
observe: (target) => {
|
|
315
|
+
setTimeout(() => {
|
|
316
|
+
callback([{ target, isIntersecting: true }], this.#instance);
|
|
317
|
+
}, 0);
|
|
318
|
+
},
|
|
319
|
+
unobserve: () => {},
|
|
320
|
+
disconnect: () => {}
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
if (!targets && type !== 'media' && debug) {
|
|
325
|
+
console.warn('QuiqlLazy (CustomLoad): "targets" parameter is missing.');
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
this.add(targets);
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
add(targets) {
|
|
332
|
+
const { type, classes, attributes, callback } = this.#config;
|
|
333
|
+
|
|
334
|
+
if (!targets) {
|
|
335
|
+
if (type === 'media') {
|
|
336
|
+
targets = document.querySelectorAll(
|
|
337
|
+
`.${classes.lazy}[${attributes.src}], .${classes.lazy}[${attributes.bg}]`
|
|
338
|
+
);
|
|
339
|
+
} else {
|
|
340
|
+
return;
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
const elements = normalizeTargets(targets);
|
|
345
|
+
|
|
346
|
+
if (this.#isRealObserver) {
|
|
347
|
+
for (const element of elements) {
|
|
348
|
+
if (element instanceof Element) {
|
|
349
|
+
this.#instance.observe(element);
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
} else {
|
|
353
|
+
const fakeEntries = [];
|
|
354
|
+
|
|
355
|
+
for (const element of elements) {
|
|
356
|
+
if (element instanceof Element) {
|
|
357
|
+
fakeEntries.push({ target: element, isIntersecting: true });
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
if (fakeEntries.length) {
|
|
362
|
+
setTimeout(() => {
|
|
363
|
+
callback(fakeEntries, this.#instance);
|
|
364
|
+
}, 0);
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
remove(targets) {
|
|
370
|
+
if (!targets) {
|
|
371
|
+
return;
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
const elements = normalizeTargets(targets);
|
|
375
|
+
|
|
376
|
+
for (const element of elements) {
|
|
377
|
+
if (element instanceof Element) {
|
|
378
|
+
this.#instance.unobserve(element);
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
clear() {
|
|
384
|
+
this.#instance.disconnect();
|
|
385
|
+
|
|
386
|
+
if (this.#config.debug) {
|
|
387
|
+
console.log('QuiqlLazy: Instance destroyed and disconnected.');
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
};
|
|
391
|
+
|
|
392
|
+
static LazyLoad = class extends QuiqlLazy.Observer {
|
|
393
|
+
constructor(settings = {}) {
|
|
394
|
+
super({ ...settings, type: 'media' });
|
|
395
|
+
}
|
|
396
|
+
};
|
|
397
|
+
|
|
398
|
+
static CustomLoad = class extends QuiqlLazy.Observer {
|
|
399
|
+
constructor(settings = {}) {
|
|
400
|
+
super({ ...settings, type: 'custom' });
|
|
401
|
+
}
|
|
402
|
+
};
|
|
403
|
+
|
|
404
|
+
static mediaCallback = (config) => {
|
|
405
|
+
const { attributes, classes, debug, onLoad, onError } = config;
|
|
406
|
+
|
|
407
|
+
const loadImage = (url, srcset, sizes) => new Promise((resolve, reject) => {
|
|
408
|
+
const img = new Image();
|
|
409
|
+
|
|
410
|
+
if (sizes) {
|
|
411
|
+
img.sizes = sizes;
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
if (srcset) {
|
|
415
|
+
img.srcset = srcset;
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
img.src = url;
|
|
419
|
+
img.onload = resolve;
|
|
420
|
+
img.onerror = reject;
|
|
421
|
+
});
|
|
422
|
+
|
|
423
|
+
return async (entry) => {
|
|
424
|
+
const target = entry.target;
|
|
425
|
+
|
|
426
|
+
target.classList.replace(classes.lazy, classes.loading);
|
|
427
|
+
|
|
428
|
+
const isImg = target instanceof HTMLImageElement;
|
|
429
|
+
const srcset = target.getAttribute(attributes.srcset);
|
|
430
|
+
const src = isImg ? target.getAttribute(attributes.src) : target.getAttribute(attributes.bg);
|
|
431
|
+
|
|
432
|
+
if (!src) {
|
|
433
|
+
if (debug) {
|
|
434
|
+
console.warn('QuiqlLazy: Missing source attribute on:', target);
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
target.classList.replace(classes.loading, classes.error);
|
|
438
|
+
|
|
439
|
+
executeCallback(onError, target);
|
|
440
|
+
|
|
441
|
+
return;
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
const sizes = isImg ? target.getAttribute('sizes') : null;
|
|
445
|
+
|
|
446
|
+
try {
|
|
447
|
+
await loadImage(src, srcset, sizes);
|
|
448
|
+
|
|
449
|
+
if (isImg) {
|
|
450
|
+
if (srcset) {
|
|
451
|
+
target.removeAttribute(attributes.srcset);
|
|
452
|
+
target.srcset = srcset;
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
target.removeAttribute(attributes.src);
|
|
456
|
+
target.src = src;
|
|
457
|
+
} else {
|
|
458
|
+
target.removeAttribute(attributes.bg);
|
|
459
|
+
target.style.backgroundImage = `url("${src}")`;
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
target.classList.replace(classes.loading, classes.loaded);
|
|
463
|
+
|
|
464
|
+
executeCallback(onLoad, target);
|
|
465
|
+
} catch(error) {
|
|
466
|
+
if (debug) {
|
|
467
|
+
console.error('QuiqlLazy: Error loading image:', src, error);
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
target.classList.replace(classes.loading, classes.error);
|
|
471
|
+
|
|
472
|
+
executeCallback(onError, target);
|
|
473
|
+
}
|
|
474
|
+
};
|
|
475
|
+
};
|
|
476
|
+
|
|
477
|
+
static customCallback = (load = null) => {
|
|
478
|
+
return () => {
|
|
479
|
+
if (isFunction(load)) {
|
|
480
|
+
load();
|
|
481
|
+
}
|
|
482
|
+
};
|
|
483
|
+
};
|
|
484
|
+
|
|
485
|
+
static processIntersection(action, { shouldUnobserve = false, shouldDisconnect = false } = {}) {
|
|
486
|
+
const isActionFunc = isFunction(action);
|
|
487
|
+
|
|
488
|
+
return (entries, observer) => {
|
|
489
|
+
for (let i = 0; i < entries.length; i++) {
|
|
490
|
+
const current = entries[i];
|
|
491
|
+
|
|
492
|
+
if (current.isIntersecting) {
|
|
493
|
+
if (shouldUnobserve) {
|
|
494
|
+
observer.unobserve(current.target);
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
if (shouldDisconnect) {
|
|
498
|
+
observer.disconnect();
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
if (isActionFunc) {
|
|
502
|
+
action(current, observer, entries);
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
if (shouldDisconnect) {
|
|
506
|
+
break;
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
};
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
static onEach = (action, shouldUnobserve = true) => {
|
|
514
|
+
return QuiqlLazy.processIntersection(action, { shouldUnobserve });
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
static onAny = (action, shouldDisconnect = true) => {
|
|
518
|
+
return QuiqlLazy.processIntersection(action, { shouldDisconnect });
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
// Вместо export default QuiqlLazy и if (isBrowser) в конце файла:
|
|
523
|
+
if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
|
|
524
|
+
module.exports = QuiqlLazy;
|
|
525
|
+
} else if (isBrowser) {
|
|
526
|
+
window.QuiqlLazy = QuiqlLazy;
|
|
527
|
+
}
|
|
528
|
+
})();
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
(()=>{const E=typeof window<"u"&&typeof document<"u",w=f=>typeof f=="function",y=(f,e)=>{if(w(f))try{f(e)}catch(t){console.error(t)}},v=f=>f?f instanceof Element?[f]:typeof f!="string"&&typeof f[Symbol.iterator]=="function"?Array.from(f):[]:[];class m{static config={shouldRunIfLoaded:!0,scanExistingResources:!1,ignoreOnScan:[],debug:!1};static#s=!1;static#e=new Map;static normalizeUrl(e){try{return new URL(e,window.location.href).href}catch(t){return this.config?.debug&&console.warn(`QuiqlLazy: Failed to normalize URL "${e}"`,t),e}}static#o(e,t="loaded"){return{element:e,status:t,loadEvent:null,errorEvent:null,onloads:new Set,onerrors:new Set}}static#c(){const e=r=>this.config.ignoreOnScan.some(i=>r.includes(i));[{sel:"script[src]",attr:"src"},{sel:'link[rel="stylesheet"][href]',attr:"href"}].forEach(({sel:r,attr:i})=>{document.querySelectorAll(r).forEach(s=>{const c=s[i];if(!c)return;const n=this.normalizeUrl(c);!e(n)&&!this.#e.has(n)&&this.#e.set(n,this.#o(s))})}),this.config.debug&&console.log(`QuiqlLazy: Scanned existing resources. Total in cache: ${this.#e.size}`)}static#n(e,t,r,i,s,c,n){e.status=i,e[s]=n,e[c].forEach(u=>{try{u(n)}catch(o){console.error("QuiqlLazy: Error in user callback",o)}}),e.onloads.clear(),e.onerrors.clear(),t.onload=null,t.onerror=null,i==="error"&&this.#e.delete(r)}static async loadResource(e,t,r={}){if(!E)return null;const i={...this.config,...r},{src:s,href:c,onload:n,onerror:u,...o}=t,b=s?"src":"href";let l=s||c;if(i.scanExistingResources&&!this.#s&&(this.#s=!0,this.#c()),!l||typeof l!="string")return i.debug&&console.warn("QuiqlLazy: url is not passed!"),null;if(l=this.normalizeUrl(l),this.#e.has(l)){const a=this.#e.get(l);if(a.status==="loaded")return i.shouldRunIfLoaded&&y(n,a.loadEvent),a.element;if(a.status==="error")throw y(u,a.errorEvent),a.errorEvent||new Error(`QuiqlLazy: Failed to load resource: ${l}`);return new Promise((h,d)=>{a.onloads.add(g=>{y(n,g),h(a.element)}),a.onerrors.add(g=>{y(u,g),d(g)})})}return new Promise((a,h)=>{const d=document.createElement(e),g=this.#o(d,"pending");w(n)&&g.onloads.add(n),w(u)&&g.onerrors.add(u),this.#e.set(l,g),d.onload=p=>{this.#n(g,d,l,"loaded","loadEvent","onloads",p),a(d)},d.onerror=p=>{i.debug&&console.error(`QuiqlLazy: Failed to load resource "${l}"`),d.parentNode&&d.parentNode.removeChild(d),this.#n(g,d,l,"error","errorEvent","onerrors",p),h(p)};for(const p in o){const z=o[p];z!=null&&z!==!1&&d.setAttribute(p,z===!0?"":String(z))}d[b]=l,(e==="link"?document.head:document.body).appendChild(d)})}static loadScript(e,t=void 0,r={}){return this.loadResource("script",{src:e,async:!0,onload:t},r)}static loadStyle(e,t=void 0,r={}){return this.loadResource("link",{href:e,rel:"stylesheet",onload:t},r)}static Observer=class{#t=null;#i=!0;#r={};static defaults={options:{root:null,rootMargin:"200px 0px",threshold:0}};static lazyDefaults={attributes:{src:"data-src",srcset:"data-srcset",bg:"data-bg"},classes:{lazy:"lazy",loading:"loading",loaded:"loaded",error:"error"}};constructor(e={}){if(!E){console.warn("QuiqlLazy: Work is only possible in a browser");return}const t=m,r=this.constructor.defaults,i=this.constructor.lazyDefaults;this.#r={...r,...e,options:{...r.options,...e.options},debug:t.config.debug};const s=this.#r;if(s.type==="media")for(const c of["attributes","classes"])s[c]={...i[c],...e[c]};w(s.callback)||(s.type==="media"?s.callback=t.onEach(t.mediaCallback(s)):s.callback=t.onAny(t.customCallback(s.load))),this.#a()}#a(){const{options:e,debug:t,type:r,targets:i,callback:s}=this.#r;E&&"IntersectionObserver"in window&&"IntersectionObserverEntry"in window&&"isIntersecting"in window.IntersectionObserverEntry.prototype?this.#t=new IntersectionObserver(s,e):(this.#i=!1,this.#t={observe:n=>{setTimeout(()=>{s([{target:n,isIntersecting:!0}],this.#t)},0)},unobserve:()=>{},disconnect:()=>{}}),!i&&r!=="media"&&t&&console.warn('QuiqlLazy (CustomLoad): "targets" parameter is missing.'),this.add(i)}add(e){const{type:t,classes:r,attributes:i,callback:s}=this.#r;if(!e)if(t==="media")e=document.querySelectorAll(`.${r.lazy}[${i.src}], .${r.lazy}[${i.bg}]`);else return;const c=v(e);if(this.#i)for(const n of c)n instanceof Element&&this.#t.observe(n);else{const n=[];for(const u of c)u instanceof Element&&n.push({target:u,isIntersecting:!0});n.length&&setTimeout(()=>{s(n,this.#t)},0)}}remove(e){if(!e)return;const t=v(e);for(const r of t)r instanceof Element&&this.#t.unobserve(r)}clear(){this.#t.disconnect(),this.#r.debug&&console.log("QuiqlLazy: Instance destroyed and disconnected.")}};static LazyLoad=class extends m.Observer{constructor(e={}){super({...e,type:"media"})}};static CustomLoad=class extends m.Observer{constructor(e={}){super({...e,type:"custom"})}};static mediaCallback=e=>{const{attributes:t,classes:r,debug:i,onLoad:s,onError:c}=e,n=(u,o,b)=>new Promise((l,a)=>{const h=new Image;b&&(h.sizes=b),o&&(h.srcset=o),h.src=u,h.onload=l,h.onerror=a});return async u=>{const o=u.target;o.classList.replace(r.lazy,r.loading);const b=o instanceof HTMLImageElement,l=o.getAttribute(t.srcset),a=b?o.getAttribute(t.src):o.getAttribute(t.bg);if(!a){i&&console.warn("QuiqlLazy: Missing source attribute on:",o),o.classList.replace(r.loading,r.error),y(c,o);return}const h=b?o.getAttribute("sizes"):null;try{await n(a,l,h),b?(l&&(o.removeAttribute(t.srcset),o.srcset=l),o.removeAttribute(t.src),o.src=a):(o.removeAttribute(t.bg),o.style.backgroundImage=`url("${a}")`),o.classList.replace(r.loading,r.loaded),y(s,o)}catch(d){i&&console.error("QuiqlLazy: Error loading image:",a,d),o.classList.replace(r.loading,r.error),y(c,o)}}};static customCallback=(e=null)=>()=>{w(e)&&e()};static processIntersection(e,{shouldUnobserve:t=!1,shouldDisconnect:r=!1}={}){const i=w(e);return(s,c)=>{for(let n=0;n<s.length;n++){const u=s[n];if(u.isIntersecting&&(t&&c.unobserve(u.target),r&&c.disconnect(),i&&e(u,c,s),r))break}}}static onEach=(e,t=!0)=>m.processIntersection(e,{shouldUnobserve:t});static onAny=(e,t=!0)=>m.processIntersection(e,{shouldDisconnect:t})}typeof module<"u"&&typeof module.exports<"u"?module.exports=m:E&&(window.QuiqlLazy=m)})();
|
package/package.json
CHANGED
|
@@ -1,6 +1,44 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "@quiql/lazy",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
|
|
6
|
-
}
|
|
1
|
+
{
|
|
2
|
+
"name": "@quiql/lazy",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"publishConfig": {
|
|
5
|
+
"access": "public"
|
|
6
|
+
},
|
|
7
|
+
"description": "Ultra-lightweight, zero-dependency JS library for lazy loading media and on-demand external resources with request deduplication, DOM caching, and IntersectionObserver support. Engineered for Core Web Vitals and Green IT.",
|
|
8
|
+
"main": "dist/quiql-lazy.js",
|
|
9
|
+
"jsdelivr": "dist/quiql-lazy.min.js",
|
|
10
|
+
"unpkg": "dist/quiql-lazy.min.js",
|
|
11
|
+
"types": "dist/quiql-lazy.d.ts",
|
|
12
|
+
"files": [
|
|
13
|
+
"dist",
|
|
14
|
+
"README.md",
|
|
15
|
+
"LICENSE"
|
|
16
|
+
],
|
|
17
|
+
"exports": {
|
|
18
|
+
".": {
|
|
19
|
+
"types": "./dist/quiql-lazy.d.ts",
|
|
20
|
+
"default": "./dist/quiql-lazy.js"
|
|
21
|
+
},
|
|
22
|
+
"./package.json": "./package.json"
|
|
23
|
+
},
|
|
24
|
+
"keywords": [
|
|
25
|
+
"quiql",
|
|
26
|
+
"lazy-load",
|
|
27
|
+
"lazyload",
|
|
28
|
+
"intersection-observer",
|
|
29
|
+
"resource-loader",
|
|
30
|
+
"dynamic-script",
|
|
31
|
+
"web-performance",
|
|
32
|
+
"green-it"
|
|
33
|
+
],
|
|
34
|
+
"author": "WebSultan",
|
|
35
|
+
"license": "MIT",
|
|
36
|
+
"repository": {
|
|
37
|
+
"type": "git",
|
|
38
|
+
"url": "https://github.com/quiql/lazy.git"
|
|
39
|
+
},
|
|
40
|
+
"bugs": {
|
|
41
|
+
"url": "https://github.com/quiql/lazy/issues"
|
|
42
|
+
},
|
|
43
|
+
"homepage": "https://github.com/quiql/lazy#readme"
|
|
44
|
+
}
|