-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimage-optimization.js
More file actions
203 lines (173 loc) · 6.96 KB
/
image-optimization.js
File metadata and controls
203 lines (173 loc) · 6.96 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
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
/**
* Image Optimization and Performance Monitoring Script
* For Vietnamese Bird's Nest Landing Page
*/
document.addEventListener('DOMContentLoaded', function() {
initImageOptimizations();
monitorImagePerformance();
initIntersectionObserver();
handleImageLoadErrors();
});
// Optimize images for better performance
function initImageOptimizations() {
const images = document.querySelectorAll('img');
images.forEach((img, index) => {
// Add loading attributes if not present
if (!img.hasAttribute('loading')) {
img.loading = index < 2 ? 'eager' : 'lazy';
}
if (!img.hasAttribute('decoding')) {
img.decoding = 'async';
}
// Add importance for hero images
if (img.closest('.hero') || img.classList.contains('product-image')) {
img.fetchPriority = 'high';
}
// Ensure proper display
img.style.opacity = '0';
img.style.transition = 'opacity 0.3s ease';
// Show image when loaded
img.addEventListener('load', function() {
this.style.opacity = '1';
});
// Handle load errors
img.addEventListener('error', function() {
console.warn('Image failed to load:', this.src);
this.style.opacity = '0.5';
this.style.filter = 'grayscale(100%)';
});
});
}
// Monitor image performance
function monitorImagePerformance() {
if ('PerformanceObserver' in window) {
const observer = new PerformanceObserver((list) => {
list.getEntries().forEach((entry) => {
if (entry.entryType === 'resource' &&
(entry.name.includes('.jpg') || entry.name.includes('.png') ||
entry.name.includes('.webp') || entry.name.includes('.avif'))) {
console.log(`Image loaded: ${entry.name}`);
console.log(`Load time: ${entry.duration}ms`);
// Alert if image takes too long to load
if (entry.duration > 2000) {
console.warn(`Slow image loading detected: ${entry.name} took ${entry.duration}ms`);
}
}
});
});
observer.observe({ entryTypes: ['resource'] });
}
}
// Use Intersection Observer for better performance
function initIntersectionObserver() {
if ('IntersectionObserver' in window) {
const imageObserver = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
// Force visibility for critical images
if (img.classList.contains('product-image') ||
img.closest('.hero') ||
img.closest('.about-image')) {
img.style.visibility = 'visible';
img.style.opacity = '1';
img.style.transform = 'none';
img.style.zIndex = '1000';
}
observer.unobserve(img);
}
});
}, {
threshold: 0.1,
rootMargin: '50px'
});
// Observe all images
document.querySelectorAll('img').forEach(img => {
imageObserver.observe(img);
});
}
}
// Handle image load errors gracefully
function handleImageLoadErrors() {
const criticalImages = document.querySelectorAll('.product-image, .hero img, .about-image img');
criticalImages.forEach(img => {
img.addEventListener('error', function() {
// Create a fallback placeholder
const placeholder = document.createElement('div');
placeholder.style.cssText = `
width: ${this.offsetWidth || 300}px;
height: ${this.offsetHeight || 300}px;
background: linear-gradient(135deg, #f8f6f3 0%, #e8e6e3 100%);
border: 2px dashed #c89678;
display: flex;
align-items: center;
justify-content: center;
color: #c89678;
font-family: 'Noto Sans JP', sans-serif;
font-size: 14px;
text-align: center;
border-radius: 12px;
`;
placeholder.innerHTML = '🖼️<br>Image Loading...';
// Replace the broken image
this.parentNode.replaceChild(placeholder, this);
// Try to reload the image after a delay
setTimeout(() => {
const newImg = document.createElement('img');
newImg.src = this.src;
newImg.className = this.className;
newImg.alt = this.alt;
newImg.style.cssText = this.style.cssText;
newImg.addEventListener('load', function() {
placeholder.parentNode.replaceChild(newImg, placeholder);
});
newImg.addEventListener('error', function() {
console.error('Image still failed to load after retry:', this.src);
});
}, 2000);
});
});
}
// Device-specific optimizations
function applyDeviceOptimizations() {
const isIPhone = /iPhone/.test(navigator.userAgent);
const isSmallScreen = window.innerWidth <= 375;
if (isIPhone && isSmallScreen) {
// Apply iPhone SE specific optimizations
document.body.classList.add('iphone-se-mode');
// Force product images to be visible
const productImages = document.querySelectorAll('.product-image, .hero-visual img');
productImages.forEach(img => {
img.style.cssText += `
position: relative !important;
z-index: 9999 !important;
visibility: visible !important;
opacity: 1 !important;
display: block !important;
transform: none !important;
animation: none !important;
will-change: auto !important;
`;
});
}
}
// Apply optimizations on load and resize
window.addEventListener('load', applyDeviceOptimizations);
window.addEventListener('resize', applyDeviceOptimizations);
// Preload critical images
function preloadCriticalImages() {
const criticalImageSources = [
// Add your critical image paths here
'./images/product-bottle.png',
'./images/hero-bg.jpg'
];
criticalImageSources.forEach(src => {
const link = document.createElement('link');
link.rel = 'preload';
link.as = 'image';
link.href = src;
document.head.appendChild(link);
});
}
// Call preload on script load
preloadCriticalImages();