home
/
u941026986
/
domains
/
irole.co
/
public_html
➕ New
📤 Upload
✎ Editing:
vite-plugin-optimize-html.ts
← Back
import type { Plugin } from 'vite'; import { readFileSync, writeFileSync } from 'fs'; import { join } from 'path'; /** * Vite plugin to optimize HTML for better Speed Index * - Makes CSS non-render-blocking using media="print" trick * - Adds preload hints for critical resources */ export function optimizeHtml(): Plugin { return { name: 'optimize-html', apply: 'build', closeBundle() { const htmlPath = join(process.cwd(), 'build', 'index.html'); try { let html = readFileSync(htmlPath, 'utf-8'); // Find all CSS link tags and make them non-render-blocking html = html.replace( /<link\s+rel="stylesheet"[^>]*>/gi, (match) => { // Skip if already has media attribute if (match.includes('media=')) { return match; } // Add media="print" and onload to make it non-blocking return match.replace( '>', ' media="print" onload="this.media=\'all\'">' ); } ); // Add noscript fallback for CSS (for browsers without JS) const noscriptMatch = html.match(/<\/noscript>/i); if (!noscriptMatch || !html.includes('<!-- noscript css -->')) { // Find the last CSS link and add noscript after it html = html.replace( /(<link[^>]*rel="stylesheet"[^>]*>)/gi, (match, linkTag) => { // Extract href from the link tag const hrefMatch = linkTag.match(/href="([^"]+)"/); if (hrefMatch) { const href = hrefMatch[1]; return `${match}\n <noscript><link rel="stylesheet" href="${href}"></noscript>`; } return match; } ); } // Add preload hints for JavaScript modules (critical for fast loading) html = html.replace( /(<script[^>]*type="module"[^>]*src="([^"]+)"[^>]*>)/gi, (match, scriptTag, src) => { // Add preload link before the script const preloadLink = ` <link rel="modulepreload" href="${src}" crossorigin>\n`; // Check if preload already exists if (!html.includes(`href="${src}"`)) { return preloadLink + ' ' + match; } return match; } ); writeFileSync(htmlPath, html, 'utf-8'); console.log('✓ HTML optimized for better Speed Index'); } catch (error) { console.warn('⚠ Could not optimize HTML:', error); } }, }; }
💾 Save Changes
Cancel
📤 Upload File
×
Select File
Upload
Cancel
➕ Create New
×
Type
📄 File
📁 Folder
Name
Create
Cancel
✎ Rename Item
×
Current Name
New Name
Rename
Cancel
🔐 Change Permissions
×
Target File
Permission (e.g., 0755, 0644)
0755
0644
0777
Apply
Cancel