-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsite-optimizer.js
More file actions
161 lines (147 loc) · 5.2 KB
/
site-optimizer.js
File metadata and controls
161 lines (147 loc) · 5.2 KB
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
const SiteOptimizer = (() => {
let state = {};
const listeners = [];
// DOM Helpers
const $ = (selector) => document.querySelector(selector);
const $$ = (selector) => document.querySelectorAll(selector);
// Event Management with Debounce and Throttle
const on = (element, event, callback) => {
if (element && event && callback) {
element.addEventListener(event, callback);
}
};
const debounce = (func, delay) => {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => func(...args), delay);
};
};
const throttle = (func, limit) => {
let lastFunc;
let lastRan;
return (...args) => {
const context = this;
if (!lastRan) {
func.apply(context, args);
lastRan = Date.now();
} else {
clearTimeout(lastFunc);
lastFunc = setTimeout(() => {
if ((Date.now() - lastRan) >= limit) {
func.apply(context, args);
lastRan = Date.now();
}
}, limit - (Date.now() - lastRan));
}
};
};
// Lazy Loading for Images and Iframes (بدون تغيير التصميم)
const lazyLoad = () => {
const lazyElements = $$('[data-lazy]');
if ('IntersectionObserver' in window) {
const observer = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
const element = entry.target;
if (element.tagName === 'IMG') {
element.src = element.dataset.src;
} else if (element.tagName === 'IFRAME') {
element.src = element.dataset.src;
}
observer.unobserve(element);
}
});
}, { rootMargin: '50px', threshold: 0.1 });
lazyElements.forEach(el => observer.observe(el));
} else {
lazyElements.forEach(el => {
if (el.tagName === 'IMG' || el.tagName === 'IFRAME') {
el.src = el.dataset.src;
}
});
}
};
// Service Worker for Caching and Offline Support
const enableCaching = () => {
if ('serviceWorker' in navigator) {
navigator.serviceWorker
.register('/service-worker.js')
.then((registration) => {
console.log('Service Worker registered with scope:', registration.scope);
})
.catch((error) => {
console.error('Service Worker registration failed:', error);
});
}
};
// Performance Monitoring with Web Vitals
const trackPerformance = () => {
import('web-vitals').then(({ getCLS, getFID, getLCP }) => {
getCLS(console.log);
getFID(console.log);
getLCP(console.log);
});
};
// Async Data Fetching with Retry and Timeout
const fetchData = async (url, options = {}, retries = 3, timeout = 5000) => {
try {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), timeout);
const response = await fetch(url, { ...options, signal: controller.signal });
clearTimeout(timeoutId);
if (!response.ok) throw new Error('Network response was not ok');
return await response.json();
} catch (error) {
if (retries > 0) {
console.log(`Retrying... ${retries} attempts left`);
return fetchData(url, options, retries - 1, timeout);
}
console.error('Fetch error:', error);
return null;
}
};
// Defer Non-Critical Scripts
const deferScripts = () => {
$$('script[data-defer]').forEach(script => {
if (script.dataset.src) {
const newScript = document.createElement('script');
newScript.src = script.dataset.src;
newScript.defer = true;
document.body.appendChild(newScript);
script.remove();
}
});
};
// Smooth Scroll with Polyfill for Older Browsers
const smoothScroll = () => {
if ('scrollBehavior' in document.documentElement.style) {
document.documentElement.style.scrollBehavior = 'smooth';
} else {
import('smoothscroll-polyfill').then((module) => {
module.polyfill();
});
}
};
// Initialize the Library
const init = () => {
lazyLoad();
enableCaching();
trackPerformance();
deferScripts();
smoothScroll();
console.log('SiteOptimizer initialized!');
};
// Public API
return {
init,
$,
$$,
on,
debounce,
throttle,
fetchData,
};
})();
// Initialize on DOM Load
document.addEventListener('DOMContentLoaded', () => SiteOptimizer.init());