Ad Code

Responsive Advertisement

Code Minifier Tool

Minifier Tool | Minify CSS, JavaScript & HTML Code Online

Code Minifier Tool

Free online tool to minify CSS, JavaScript, and HTML code. Reduce file size, improve loading speed, and optimize website performance.

Input Code

Upload Code Files

Drag & drop files or click to browse

Supports .css, .js, .html files (Max 10MB)

Browse Files
Original Code 0 characters

Minification Options

Minified Output

0
Original Size
0
Minified Size
0%
Reduction
0 KB
Saved
Minified Code 0 characters
0ms
Estimated Load Time
0%
Speed Improvement
0
Mobile Score

Code Examples

Before Minification After Minification
/* Before Minification */ .container { margin: 0 auto; max-width: 1200px; padding: 20px; } .button { background-color: #3498db; border: none; border-radius: 4px; color: white; padding: 10px 20px; font-size: 16px; cursor: pointer; } /* After Minification */ .container{margin:0 auto;max-width:1200px;padding:20px}.button{background-color:#3498db;border:none;border-radius:4px;color:#fff;padding:10px 20px;font-size:16px;cursor:pointer}

Performance Impact of Code Minification

Code minification significantly improves website performance by reducing file sizes and optimizing delivery. Here's how minification affects different aspects of web performance:

Metric Before Minification After Minification Improvement
File Size 150KB (CSS) + 250KB (JS) 90KB (CSS) + 150KB (JS) 40% Reduction
Load Time (3G) 4.2 seconds 2.8 seconds 33% Faster
Bandwidth Usage 400KB per visit 240KB per visit 40% Less
Time to Interactive 3.5 seconds 2.2 seconds 37% Faster

How Minification Affects SEO Rankings

Search engines like Google consider page speed as a ranking factor. By minifying your code, you can:

  • Improve Core Web Vitals: Better LCP, FID, and CLS scores
  • Reduce Bounce Rates: Faster loading pages keep users engaged
  • Increase Crawl Budget: Search engines can crawl more pages faster
  • Mobile-First Indexing: Better performance on mobile devices
  • Enhanced User Experience: Faster interactions and smoother navigation

Real-World Performance Benefits

15-25%
SEO Improvement
20-40%
Conversion Boost
35%
Bandwidth Savings

CSS Minification Guide

What CSS Minification Does

CSS minification removes unnecessary characters from your stylesheets without changing functionality:

  • Removes whitespace: Spaces, tabs, and line breaks
  • Eliminates comments: All /* */ comments are removed
  • Shortens colors: #FFFFFF becomes #fff, rgb(255,255,255) becomes #fff
  • Optimizes properties: margin: 0px 0px 0px 0px becomes margin:0
  • Removes semicolons: Last semicolon in rules is removed

Example of CSS Minification:

/* Original CSS (187 bytes) */ .header { background-color: #ffffff; color: #333333; padding: 20px 15px; margin: 0 auto; font-family: Arial, sans-serif; } /* Minified CSS (79 bytes) */ .header{background-color:#fff;color:#333;padding:20px 15px;margin:0 auto;font-family:Arial,sans-serif}

Advanced CSS Optimization

Beyond basic minification, you can optimize CSS further:

  • Merge duplicate rules: Combine identical selectors
  • Remove unused CSS: Eliminate styles not used on the page
  • Optimize animations: Use transform instead of position changes
  • Critical CSS extraction: Load above-the-fold CSS first
  • CSS nesting: Use modern nesting for better organization

JavaScript Minification Guide

JavaScript Minification Techniques

JavaScript minification goes beyond removing whitespace. It includes:

  • Variable name shortening: Long variable names become single letters
  • Removal of dead code: Unused functions and variables are eliminated
  • String compression: Long strings are optimized
  • Ternary optimization: Convert if-else statements to ternary operators
  • Constant folding: Calculate constant expressions at compile time

Example of JavaScript Minification:

// Original JavaScript (254 bytes) function calculateTotalPrice(items) { let total = 0; for (let i = 0; i < items.length; i++) { total += items[i].price * items[i].quantity; } return total; } // Minified JavaScript (64 bytes) function calculateTotalPrice(t){let n=0;for(let r=0;r

Advanced JavaScript Optimization

For production JavaScript, consider these optimizations:

  • Tree shaking: Remove unused exports from modules
  • Code splitting: Split code into smaller chunks
  • Lazy loading: Load JavaScript only when needed
  • Module concatenation: Combine multiple modules into one
  • Polyfill optimization: Include only necessary polyfills

HTML Minification Guide

HTML Minification Process

HTML minification focuses on reducing file size while maintaining structure:

  • Remove whitespace: Between tags and text nodes
  • Strip comments: Remove <!-- comments -->
  • Minimize attributes: Remove quotes where possible
  • Remove optional tags: <html>, <head>, <body> can be omitted
  • Collapse boolean attributes: disabled="disabled" becomes disabled

Example of HTML Minification:

<!-- Original HTML (278 bytes) --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Example Page</title> <link rel="stylesheet" href="styles.css"> </head> <body> <div class="container"> <h1>Welcome</h1> <p>This is an example paragraph.</p> </div> </body> </html> <!-- Minified HTML (155 bytes) --> <!DOCTYPE html><html lang=en><head><meta charset=UTF-8><title>Example Page</title><link rel=stylesheet href=styles.css></head><body><div class=container><h1>Welcome</h1><p>This is an example paragraph.</p></div></body></html>

HTML Best Practices

Combine minification with these HTML optimizations:

  • Remove inline styles: Move to external CSS files
  • Optimize images: Use proper formats and compression
  • Lazy load content: Load below-the-fold content later
  • Use semantic HTML: Better for accessibility and SEO
  • Implement caching: Set proper cache headers

Frequently Asked Questions

Is minified code harder to debug?

Minified code is not meant for debugging. Always keep the original unminified source files for development and debugging. In production, you can use source maps to map minified code back to the original source for debugging purposes. Modern browsers support source maps that allow you to debug the original source code even when running minified code.

How much size reduction can I expect?

Typical size reductions vary by code type:

  • CSS: 20-50% reduction (average 30-40%)
  • JavaScript: 30-60% reduction (average 40-50%)
  • HTML: 15-40% reduction (average 20-30%)

The actual reduction depends on your code structure, comments, whitespace usage, and optimization level.

Does minification affect functionality?

Proper minification should not affect functionality. However, aggressive minification with variable renaming and code removal can sometimes break functionality if not done carefully. Always test minified code thoroughly before deploying to production. This tool uses safe minification techniques that preserve functionality while maximizing size reduction.

Should I minify code on the server or client?

It's best to minify code during your build process, not in production. Here's why:

  • Build-time minification: Minify once during deployment
  • Server-side minification: Use compression (gzip, Brotli)
  • CDN optimization: Many CDNs auto-minify content
  • Client-side: Only for development/testing tools

This tool is ideal for development testing and small projects. For production, integrate minification into your CI/CD pipeline.

Best Practices for Code Minification

Development Workflow

  • Keep original source files: Never edit minified files directly
  • Use version control: Track changes in unminified source
  • Automate the process: Integrate minification into your build tools
  • Test thoroughly: Always test minified code before deployment
  • Use source maps: For debugging production issues

Production Deployment

  • Combine with compression: Use gzip or Brotli after minification
  • Implement caching: Set long cache times for minified files
  • Use CDN: Deliver minified files through a CDN
  • Monitor performance: Track loading times and file sizes
  • Regular updates: Re-minify when source code changes

Security Considerations

  • Validate input: Never minify untrusted code
  • Check for vulnerabilities: Minification can expose certain issues
  • Sanitize output: Ensure minified code is safe
  • Update regularly: Keep minification tools current
  • Backup originals: Always keep backup of source files

Pro Tip: Build Process Integration

For optimal results, integrate minification into your build process:

  1. Use Webpack, Rollup, or Parcel for JavaScript bundling
  2. Implement PostCSS with cssnano for CSS optimization
  3. Use html-minifier-terser for HTML minification
  4. Automate with npm scripts or CI/CD pipelines
  5. Implement cache busting with file hashing

Code Minifier Tool © 2025 | Made with for web developers

All processing happens locally in your browser. Your code is never uploaded to any server.

`, after: `Example Page

Welcome to Our Website

This is an example paragraph with some text.

` } }; // Initialize document.addEventListener('DOMContentLoaded', () => { updateStats(); loadExample('css'); // Initialize FAQ accordion faqItems.forEach(item => { const question = item.querySelector('.faq-question'); question.addEventListener('click', () => { faqItems.forEach(otherItem => { if (otherItem !== item) otherItem.classList.remove('active'); }); item.classList.toggle('active'); }); }); // Example tabs exampleTabs.forEach(tab => { tab.addEventListener('click', () => { exampleTabs.forEach(t => t.classList.remove('active')); tab.classList.add('active'); loadExample(tab.dataset.example); }); }); // Smooth scrolling document.querySelectorAll('a[href^="#"]').forEach(anchor => { anchor.addEventListener('click', function(e) { e.preventDefault(); const targetId = this.getAttribute('href'); if (targetId === '#') return; const targetElement = document.querySelector(targetId); if (targetElement) { window.scrollTo({ top: targetElement.offsetTop - 80, behavior: 'smooth' }); } }); }); // Set initial example code inputCode.value = examples.css.before; updateStats(); }); // Show status message function showStatus(message, isError = false) { statusMessage.textContent = message; statusMessage.className = 'status-message' + (isError ? ' error' : ''); statusMessage.classList.add('show'); setTimeout(() => { statusMessage.classList.remove('show'); }, 3000); } // Update stats function updateStats() { const inputText = inputCode.value; const outputText = outputCode.value; const inputLength = inputText.length; const outputLength = outputText.length; // Update info displays inputInfo.textContent = `${inputLength.toLocaleString()} characters`; outputInfo.textContent = `${outputLength.toLocaleString()} characters`; // Update stats originalSize.textContent = formatBytes(inputLength); minifiedSize.textContent = formatBytes(outputLength); if (inputLength > 0) { const reduction = ((inputLength - outputLength) / inputLength * 100).toFixed(1); const saved = inputLength - outputLength; reductionPercent.textContent = `${reduction}%`; savedBytes.textContent = formatBytes(saved); // Update performance metrics const estimatedLoadTime = Math.max(100, Math.round(inputLength / 5000)); // Rough estimate const improvedLoadTime = Math.max(50, Math.round(outputLength / 5000)); const improvement = ((estimatedLoadTime - improvedLoadTime) / estimatedLoadTime * 100).toFixed(0); loadTime.textContent = `${improvedLoadTime}ms`; speedImprovement.textContent = `${improvement}%`; mobileScore.textContent = Math.min(100, Math.max(0, 100 - improvedLoadTime / 2)); } else { reductionPercent.textContent = '0%'; savedBytes.textContent = '0 KB'; loadTime.textContent = '0ms'; speedImprovement.textContent = '0%'; mobileScore.textContent = '0'; } } // Format bytes to readable format function formatBytes(bytes) { if (bytes === 0) return '0 Bytes'; const k = 1024; const sizes = ['Bytes', 'KB', 'MB', 'GB']; const i = Math.floor(Math.log(bytes) / Math.log(k)); return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]; } // Load example function loadExample(type) { currentType = type; exampleCode.textContent = `/* Before Minification (${formatBytes(examples[type].before.length)}) */\n${examples[type].before}\n\n/* After Minification (${formatBytes(examples[type].after.length)}) */\n${examples[type].after}`; // Update active type button typeBtns.forEach(btn => { if (btn.dataset.type === type) { btn.classList.add('active'); } else { btn.classList.remove('active'); } }); } // Type button event listeners typeBtns.forEach(btn => { btn.addEventListener('click', () => { typeBtns.forEach(b => b.classList.remove('active')); btn.classList.add('active'); currentType = btn.dataset.type; loadExample(currentType); // Update placeholder based on type const placeholders = { css: 'Paste your CSS code here...', js: 'Paste your JavaScript code here...', html: 'Paste your HTML code here...' }; inputCode.placeholder = placeholders[currentType] || 'Paste your code here...'; showStatus(`Switched to ${currentType.toUpperCase()} mode`); }); }); // Minify function function minifyCode(code, type) { let minified = code; // Common minification steps if (removeWhitespace.checked) { minified = minified.replace(/\s+/g, ' '); // Replace multiple spaces with single space } if (removeComments.checked) { if (type === 'css' || type === 'js') { minified = minified.replace(/\/\*[\s\S]*?\*\//g, ''); // Remove CSS/JS block comments minified = minified.replace(/\/\/.*$/gm, ''); // Remove JS line comments } if (type === 'html') { minified = minified.replace(//g, ''); // Remove HTML comments } } // Type-specific minification if (type === 'css') { minified = minifyCSS(minified); } else if (type === 'js') { minified = minifyJS(minified); } else if (type === 'html') { minified = minifyHTML(minified); } // Final cleanup minified = minified.trim(); minified = minified.replace(/\s*([{};:,])\s*/g, '$1'); // Remove spaces around special chars minified = minified.replace(/;\s*}/g, '}'); // Remove last semicolon before closing brace minified = minified.replace(/\s+/g, ' '); // Collapse multiple spaces return minified; } // CSS-specific minification function minifyCSS(css) { let minified = css; // Remove whitespace minified = minified.replace(/\s*([{}:;,])\s*/g, '$1'); minified = minified.replace(/;\s*}/g, '}'); // Shorten hex colors if enabled if (shortenHex.checked) { minified = minified.replace(/#([a-fA-F0-9])\1([a-fA-F0-9])\2([a-fA-F0-9])\3/g, '#$1$2$3'); } // Optimize zero values minified = minified.replace(/:0px/g, ':0'); minified = minified.replace(/:0em/g, ':0'); minified = minified.replace(/:0rem/g, ':0'); // Remove unnecessary units for zero minified = minified.replace(/(\s|:)0(\.\d+)?(px|em|rem|%|vh|vw)/g, '$10'); return minified.trim(); } // JavaScript-specific minification function minifyJS(js) { let minified = js; // Basic minification minified = minified.replace(/\/\/.*$/gm, ''); // Remove line comments minified = minified.replace(/\/\*[\s\S]*?\*\//g, ''); // Remove block comments minified = minified.replace(/\s*([=+\-*\/%&|^<>?~!{}();:,.[\]])+\s*/g, '$1'); // Remove spaces around operators minified = minified.replace(/\s+/g, ' '); // Collapse multiple spaces // Advanced minification (simplified) if (minifyJsVars.checked) { // Simple variable name shortening (for demonstration) minified = minified.replace(/\bvar\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g, 'var $1'); minified = minified.replace(/\blet\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g, 'let $1'); minified = minified.replace(/\bconst\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g, 'const $1'); } // Remove trailing semicolons minified = minified.replace(/;\s*$/gm, ''); return minified.trim(); } // HTML-specific minification function minifyHTML(html) { let minified = html; // Remove HTML comments minified = minified.replace(//g, ''); // Remove whitespace between tags minified = minified.replace(/>\s+<'); // Remove whitespace at beginning and end of lines minified = minified.replace(/^\s+|\s+$/gm, ''); // Remove quotes from attributes where possible minified = minified.replace(/\s+([a-zA-Z-]+)="([^"]*)"/g, function(match, attr, value) { if (/^[a-zA-Z0-9-_\.]+$/.test(value)) { return ' ' + attr + '=' + value; } return match; }); // Collapse multiple spaces minified = minified.replace(/\s+/g, ' '); return minified.trim(); } // Beautify function function beautifyCode(code, type) { let beautified = code; // Basic formatting if (type === 'css') { beautified = beautified.replace(/}/g, '}\n'); beautified = beautified.replace(/{/g, ' {\n '); beautified = beautified.replace(/;/g, ';\n '); beautified = beautified.replace(/\s+/g, ' '); } else if (type === 'js') { beautified = beautified.replace(/;/g, ';\n'); beautified = beautified.replace(/{/g, ' {\n'); beautified = beautified.replace(/}/g, '\n}\n'); } else if (type === 'html') { beautified = beautified.replace(/><\/g, '>\n/g, '>\n'); } return beautified.trim(); } // Event Listeners // Minify button minifyBtn.addEventListener('click', () => { const code = inputCode.value.trim(); if (!code) { showStatus('Please enter code to minify', true); return; } minifiedCode = minifyCode(code, currentType); outputCode.value = minifiedCode; updateStats(); showStatus(`${currentType.toUpperCase()} code minified successfully!`); }); // Beautify button beautifyBtn.addEventListener('click', () => { const code = inputCode.value.trim(); if (!code) { showStatus('Please enter code to beautify', true); return; } const beautified = beautifyCode(code, currentType); inputCode.value = beautified; updateStats(); showStatus(`Code beautified for ${currentType.toUpperCase()}`); }); // Clear input button clearInputBtn.addEventListener('click', () => { inputCode.value = ''; outputCode.value = ''; updateStats(); showStatus('Input cleared'); }); // Copy output button copyOutputBtn.addEventListener('click', () => { if (!outputCode.value.trim()) { showStatus('No minified code to copy', true); return; } outputCode.select(); document.execCommand('copy'); showStatus('Minified code copied to clipboard!'); }); // Download button downloadBtn.addEventListener('click', () => { if (!outputCode.value.trim()) { showStatus('No minified code to download', true); return; } const blob = new Blob([outputCode.value], { type: 'text/plain' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = `minified.${currentType}`; document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(url); showStatus(`Minified ${currentType.toUpperCase()} file downloaded`); }); // Compare button compareBtn.addEventListener('click', () => { if (!inputCode.value.trim() || !outputCode.value.trim()) { showStatus('Both input and output must have code to compare', true); return; } // Create a simple comparison view const originalLines = inputCode.value.split('\n').length; const minifiedLines = outputCode.value.split('\n').length; const originalChars = inputCode.value.length; const minifiedChars = outputCode.value.length; const comparison = `=== CODE COMPARISON === Type: ${currentType.toUpperCase()} Original: ${originalLines} lines, ${originalChars} characters Minified: ${minifiedLines} lines, ${minifiedChars} characters Reduction: ${((originalChars - minifiedChars) / originalChars * 100).toFixed(1)}% Lines removed: ${originalLines - minifiedLines}`; alert(comparison); showStatus('Comparison displayed'); }); // File upload handling fileUpload.addEventListener('change', function(e) { const files = e.target.files; if (!files.length) return; const file = files[0]; const reader = new FileReader(); reader.onload = function(event) { const content = event.target.result; inputCode.value = content; // Detect file type from extension const extension = file.name.split('.').pop().toLowerCase(); if (extension === 'css') { currentType = 'css'; typeBtns.forEach(btn => { if (btn.dataset.type === 'css') { btn.classList.add('active'); } else { btn.classList.remove('active'); } }); } else if (extension === 'js') { currentType = 'js'; typeBtns.forEach(btn => { if (btn.dataset.type === 'js') { btn.classList.add('active'); } else { btn.classList.remove('active'); } }); } else if (extension === 'html') { currentType = 'html'; typeBtns.forEach(btn => { if (btn.dataset.type === 'html') { btn.classList.add('active'); } else { btn.classList.remove('active'); } }); } updateStats(); showStatus(`File "${file.name}" loaded (${formatBytes(content.length)})`); }; reader.readAsText(file); }); // Drag and drop for file upload fileUploadArea.addEventListener('dragover', (e) => { e.preventDefault(); fileUploadArea.style.borderColor = 'var(--secondary-color)'; fileUploadArea.style.background = '#f0f7ff'; }); fileUploadArea.addEventListener('dragleave', () => { fileUploadArea.style.borderColor = '#ddd'; fileUploadArea.style.background = 'white'; }); fileUploadArea.addEventListener('drop', (e) => { e.preventDefault(); fileUploadArea.style.borderColor = '#ddd'; fileUploadArea.style.background = 'white'; const files = e.dataTransfer.files; if (files.length) { fileUpload.files = files; const event = new Event('change', { bubbles: true }); fileUpload.dispatchEvent(event); } }); // Real-time stats update inputCode.addEventListener('input', updateStats); outputCode.addEventListener('input', updateStats); // Initialize with example setTimeout(() => { inputCode.value = examples.css.before; updateStats(); }, 100);

Post a Comment

0 Comments

Close Menu