/** * 🔧 CORREÇÃO ESPECÍFICA PARA PROBLEMAS DE IMAGENS NA HOSTINGER - MOBILE * * Este script resolve problemas comuns de carregamento de imagens na Hostinger * especialmente em dispositivos móveis, incluindo: * - Cache problemático * - Lazy loading conflitante * - URLs relativas vs absolutas * - Compressão de imagens * - Piscamento durante carregamento */ (function() { 'use strict'; // Configurações const CONFIG = { // Tempo máximo para carregar imagem (ms) timeout: 10000, // Intervalo para verificar carregamento (ms) checkInterval: 500, // Número máximo de tentativas maxRetries: 3, // URLs que devem ser corrigidas problematicUrls: [ 'xguiacompleto.shop', 'americanburguer.shop' ], // Fallback para imagens que não carregam fallbackImage: 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjAwIiBoZWlnaHQ9IjIwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cmVjdCB3aWR0aD0iMTAwJSIgaGVpZ2h0PSIxMDAlIiBmaWxsPSIjZjVmNWY1Ii8+PHRleHQgeD0iNTAlIiB5PSI1MCUiIGZvbnQtZmFtaWx5PSJBcmlhbCwgc2Fucy1zZXJpZiIgZm9udC1zaXplPSIxNCIgZmlsbD0iIzk5OTk5OSIgdGV4dC1hbmNob3I9Im1pZGRsZSIgZHk9Ii4zZW0iPkltYWdlbSBuw6NvIGRpc3BvbsOtdmVsPC90ZXh0Pjwvc3ZnPg==' }; // Detectar se é dispositivo móvel const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent); // Classe para gerenciar imagens class ImageManager { constructor() { this.images = new Map(); this.retryCount = new Map(); this.init(); } init() { // Aguardar DOM estar pronto if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => this.setup()); } else { this.setup(); } } setup() { console.log('🔧 Iniciando correção de imagens para Hostinger Mobile'); // Processar imagens existentes this.processExistingImages(); // Observar novas imagens this.observeNewImages(); // Forçar recarregamento em mobile if (isMobile) { this.forceMobileReload(); } } processExistingImages() { const images = document.querySelectorAll('img'); images.forEach(img => this.processImage(img)); } observeNewImages() { // Observer para novas imagens const observer = new MutationObserver((mutations) => { mutations.forEach((mutation) => { mutation.addedNodes.forEach((node) => { if (node.nodeType === 1) { // Element node if (node.tagName === 'IMG') { this.processImage(node); } else { const images = node.querySelectorAll('img'); images.forEach(img => this.processImage(img)); } } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); } processImage(img) { // Evitar processar a mesma imagem múltiplas vezes if (this.images.has(img)) { return; } this.images.set(img, true); // Adicionar classes de estado img.classList.add('img-loading'); // Corrigir URL se necessário this.fixImageUrl(img); // Configurar eventos this.setupImageEvents(img); // Forçar recarregamento em mobile if (isMobile) { this.forceImageReload(img); } // Verificar se já carregou this.checkImageLoaded(img); } fixImageUrl(img) { const src = img.src; // Corrigir URLs problemáticas CONFIG.problematicUrls.forEach(problematicUrl => { if (src.includes(problematicUrl)) { // Tentar corrigir para URL local const localPath = src.replace(/^https?:\/\/[^\/]+/, ''); if (localPath !== src) { img.src = localPath; console.log(`🔧 URL corrigida: ${src} → ${localPath}`); } } }); // Adicionar timestamp para forçar recarregamento em mobile if (isMobile && src.includes('wp-content/uploads')) { const separator = src.includes('?') ? '&' : '?'; const timestamp = Date.now(); img.src = `${src}${separator}v=${timestamp}`; } } setupImageEvents(img) { // Evento de carregamento bem-sucedido img.addEventListener('load', () => { img.classList.remove('img-loading'); img.classList.add('img-loaded'); this.retryCount.delete(img); console.log(`✅ Imagem carregada: ${img.src}`); }); // Evento de erro img.addEventListener('error', () => { this.handleImageError(img); }); // Verificar se já carregou if (img.complete) { if (img.naturalHeight > 0) { img.classList.remove('img-loading'); img.classList.add('img-loaded'); } else { this.handleImageError(img); } } } handleImageError(img) { const retries = this.retryCount.get(img) || 0; if (retries < CONFIG.maxRetries) { // Tentar novamente this.retryCount.set(img, retries + 1); console.log(`🔄 Tentativa ${retries + 1} para: ${img.src}`); setTimeout(() => { this.retryImage(img); }, CONFIG.checkInterval * (retries + 1)); } else { // Aplicar fallback this.applyFallback(img); } } retryImage(img) { const originalSrc = img.src; // Remover timestamp se existir const cleanSrc = originalSrc.replace(/[?&]v=\d+/, ''); // Adicionar novo timestamp const separator = cleanSrc.includes('?') ? '&' : '?'; const timestamp = Date.now(); img.src = `${cleanSrc}${separator}v=${timestamp}`; console.log(`🔄 Recarregando: ${cleanSrc}`); } applyFallback(img) { img.src = CONFIG.fallbackImage; img.alt = 'Imagem não disponível'; img.classList.remove('img-loading'); img.classList.add('img-error'); console.log(`❌ Fallback aplicado para: ${img.src}`); } checkImageLoaded(img) { const startTime = Date.now(); const check = () => { if (img.complete) { if (img.naturalHeight > 0) { img.classList.remove('img-loading'); img.classList.add('img-loaded'); return; } } if (Date.now() - startTime > CONFIG.timeout) { this.handleImageError(img); return; } setTimeout(check, CONFIG.checkInterval); }; check(); } forceImageReload(img) { // Forçar recarregamento usando técnicas específicas para mobile const originalSrc = img.src; // Técnica 1: Clonar e substituir const clone = img.cloneNode(true); img.parentNode.replaceChild(clone, img); // Técnica 2: Forçar GPU acceleration clone.style.transform = 'translateZ(0)'; clone.style.webkitTransform = 'translateZ(0)'; // Técnica 3: Prevenir cache clone.style.webkitBackfaceVisibility = 'hidden'; clone.style.backfaceVisibility = 'hidden'; console.log(`🔄 Forçando recarregamento mobile: ${originalSrc}`); } forceMobileReload() { // Forçar recarregamento de todas as imagens em mobile const images = document.querySelectorAll('img[src*="wp-content/uploads"]'); images.forEach((img, index) => { setTimeout(() => { this.forceImageReload(img); }, index * 100); // Delay para não sobrecarregar }); } } // Função para limpar cache do navegador function clearImageCache() { if ('caches' in window) { caches.keys().then(names => { names.forEach(name => { caches.delete(name); }); }); } } // Função para forçar recarregamento da página function forcePageReload() { if (isMobile) { // Em mobile, forçar recarregamento sem cache window.location.reload(true); } } // Função para verificar conectividade function checkConnectivity() { return navigator.onLine; } // Função para otimizar performance function optimizePerformance() { // Desabilitar lazy loading problemático const images = document.querySelectorAll('img[loading="lazy"]'); images.forEach(img => { img.loading = 'auto'; }); // Forçar GPU acceleration const style = document.createElement('style'); style.textContent = ` img { -webkit-transform: translateZ(0); transform: translateZ(0); -webkit-backface-visibility: hidden; backface-visibility: hidden; } `; document.head.appendChild(style); } // Inicializar quando DOM estiver pronto if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { new ImageManager(); optimizePerformance(); }); } else { new ImageManager(); optimizePerformance(); } // Adicionar funções globais para debug window.ImageFix = { clearCache: clearImageCache, forceReload: forcePageReload, checkConnectivity: checkConnectivity, isMobile: isMobile }; console.log('🔧 Script de correção de imagens carregado'); console.log(`📱 Dispositivo móvel: ${isMobile}`); })();