-
Notifications
You must be signed in to change notification settings - Fork 0
/
ImgPreload.js
264 lines (233 loc) · 9.29 KB
/
ImgPreload.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
const cache = new Map();
let maxCacheSize = 50; // elements limit in the cache
let cacheDuration = 30 * 60 * 1000 // Cache lifetime in milliseconds (here, 30 minutes)
let memoryThreshold = 100; // Memory threshold in Megabytes
const expiredResources = [];
let cacheCleaner;
class PriorityQueue {
constructor() {
this.queue = [];
}
enqueue(item, priority) {
this.queue.push({ item, priority });
this.queue.sort((a, b) => a.priority - b.priority);
}
dequeue() {
return this.queue.shift();
}
isEmpty() {
return this.queue.length === 0;
}
}
const priorityQueue = new PriorityQueue();
function preloadImage(url, priority = 1) {
return new Promise((resolve, reject) => {
if (isExternalURL(url)) {
fetch(url)
.then(response => response.blob())
.then(blob => {
const imgUrl = URL.createObjectURL(blob);
const img = new Image();
img.onload = () => {
cache.set(url, img);
console.log(`Image ${url} loaded and cached.`);
if (cache.size > maxCacheSize) {
cache.delete(cache.keys().next().value);
}
resolve(img.src);
};
img.onerror = reject;
img.src = imgUrl;
priorityQueue.enqueue(url, priority);
})
.catch(error => {
console.error(`Error loading image from external URL: ${url}`, error);
reject(error);
});
} else {
const img = new Image();
img.onload = () => {
cache.set(url, img);
console.log(`Image ${url} loaded and cached.`);
if (cache.size > maxCacheSize) {
cache.delete(cache.keys().next().value);
}
resolve(img.src);
};
img.onerror = reject;
img.src = url;
priorityQueue.enqueue(url, priority);
}
});
}
function cleanCache(){
const currentTime = new Date().getTime();
while (expiredResources.length > 0 && expiredResources[0].expiryTime < currentTime){
const expiredResource = expiredResources.shift();
cache.delete(expiredResource.url);
console.log(`Resource ${expiredResource.url} was removed from cache because it exceeded its lifetime.`);
}
}
function adjustCacheSize(){
const memoryInfo = window.performance.memory;
if (memoryInfo && memoryInfo.total){
const totalMemoryInMB = memoryInfo.total / (1024 * 1024);
if (totalMemoryInMB < memoryThreshold && maxCacheSize > 10){
maxCacheSize = Math.floor(maxCacheSize * 0.9);
}else if (totalMemoryInMB > memoryThreshold && maxCacheSize < 100){
maxCacheSize = Math.ceil(maxCacheSize * 1.1);
}
}
}
function preloadMedia(url, mediaElement) {
return new Promise((resolve, reject) => {
const priority = mediaElement.getAttribute('data-preload-priority') || 1;
if (isExternalURL(url)) {
fetch(url)
.then(response => response.blob())
.then(blob => {
const mediaUrl = URL.createObjectURL(blob);
mediaElement.oncanplaythrough = () => {
cache[url] = mediaElement;
resolve(mediaElement);
};
mediaElement.onerror = (error) => {
console.error(`Error loading ${url}`, error);
reject(error);
};
mediaElement.src = mediaUrl;
priorityQueue.enqueue(url, priority);
})
.catch(error => {
console.error(`Error loading media from external URL: ${url}`, error);
reject(error);
});
} else {
if (cache[url]) {
resolve(cache[url]);
} else {
mediaElement.oncanplaythrough = () => {
cache[url] = mediaElement;
resolve(mediaElement);
};
mediaElement.onerror = (error) => {
console.error(`Error loading ${url}`, error);
reject(error);
};
mediaElement.src = url;
priorityQueue.enqueue(url, priority);
}
}
});
}
function isExternalURL(url) {
return url.startsWith('http://') || url.startsWith('https://');
}
async function preloadAndShowImage(url, imgElement) {
try {
const cachedImage = await preloadImage(url);
imgElement.src = cachedImage;
console.log(`Preloading and displaying successfully : ${url}`);
} catch (error) {
console.error(`Error while preloading : ${url}`, error);
throw new Error(`Error while preloading : ${url}`);
}
}
async function preloadAndShowMediaResource(url, mediaElement) {
try {
if (!cache[url]) {
const cachedMedia = await preloadMedia(url, mediaElement);
cache[url] = cachedMedia;
}
mediaElement.src = cache[url].src;
console.log(`Preloading and displaying successfully : ${url}`);
} catch (error) {
console.error(`Error while preloading : ${url}`, error);
throw new Error(`Error while preloading : ${url}`);
}
}
async function preloadAndApplyBackground() {
const elementsWithDataBg = document.querySelectorAll('[data-background]');
for (const element of elementsWithDataBg) {
const dataBg = element.getAttribute('data-background');
if (dataBg && !cache[dataBg]) {
try {
await preloadImage(dataBg);
element.style.backgroundImage = `url('${dataBg}')`;
console.log(`Successful preloading and background application : ${dataBg}`);
} catch (error) {
console.error(`Error preloading background : ${dataBg}`, error);
}
}
}
}
async function preloadAndShowImages() {
const imgElements = document.querySelectorAll('img[data-src]');
for (const img of imgElements) {
const dataSrc = img.getAttribute('data-src');
if (dataSrc && !cache[dataSrc]) {
await preloadAndShowImage(dataSrc, img);
}
}
await preloadAndApplyBackground();
}
async function preloadAndShowMedia() {
const audioElements = document.querySelectorAll('audio[data-src]');
const videoElements = document.querySelectorAll('video[data-src]');
for (const audio of audioElements) {
const dataSrc = audio.getAttribute('data-src');
if (dataSrc && !cache[dataSrc]) {
await preloadAndShowMediaResource(dataSrc, audio);
}
}
for (const video of videoElements) {
const dataSrc = video.getAttribute('data-src');
if (dataSrc && !cache[dataSrc]) {
await preloadAndShowMediaResource(dataSrc, video);
}
}
}
setInterval(adjustCacheSize, 10 * 60 * 1000); // Adjust cache size every 10 minutes
window.ImgPreload = {
preloadAndShowImages: preloadAndShowImages,
preloadAndShowMedia: preloadAndShowMedia,
setPreloadMemory: function(quantity){
memoryThreshold = quantity;
const elements = document.querySelectorAll('img, audio, video');
elements.forEach(element => {
const tagName = element.tagName.toLowerCase();
if ((tagName === 'img' || tagName === 'audio' || tagName === 'video') && !element.dataset.preloadMemory) {
element.dataset.preloadMemory = quantity;
}
});
console.log(`Preload memory set to ${quantity} MB for selected elements`);
},
setPreloadCacheSize: function(size){
maxCacheSize = size;
const elements = document.querySelectorAll('img, video, audio');
elements.forEach(element => {
const tagName = element.tagName.toLocaleLowerCase();
if ((tagName === 'img' || tagName === 'audio' || tagName === 'video') && !element.dataset.preloadCacheSize) {
element.dataset.preloadCacheSize = size;
}
});
console.log(`Preload cache size set to ${size} for selected elements`);
},
setCacheDuration: function(durationInMilliseconds){
cacheDuration = durationInMilliseconds;
const elements = document.querySelectorAll('img, audio, video');
elements.forEach(element => {
const tagName = element.tagName.toLowerCase();
if ((tagName === 'img' || tagName === 'audio' || tagName === 'video') && !element.dataset.cacheDuration) {
element.dataset.cacheDuration = durationInMilliseconds;
}
});
console.log(`Cache duration set to ${durationInMilliseconds} ms for selected elements`);
},
setCacheCleanInterval: function(intervalInMilliseconds = 300000){
cacheDuration = intervalInMilliseconds ;
clearInterval(cacheCleaner);
cacheCleaner = setInterval(cleanCache, intervalInMilliseconds);
console.log(`Cache cleaning interval set to ${intervalInMilliseconds} ms`);
}
};