Published on April 3, 2024 · 5 min read
Working with Data URIs and Base64
Learn how to embed images and files in HTML/CSS using Base64 encoded Data URIs.
What are Data URIs?
Data URIs (or data URLs) allow you to embed small files directly into HTML or CSS as base64-encoded strings. They begin with 'data:' followed by an optional MIME type, and the base64-encoded data. This eliminates the need for separate HTTP requests for small resources.
// Data URI Structure data:[<media type>][;base64],<data> // Example data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA...
Common Use Cases
- Small images in HTML/CSS (icons, logos)
- Custom fonts using @font-face
- SVG images in CSS backgrounds
- Small audio files for web applications
- Embedding PDF files inline
Converting Files to Data URIs
Here's how to convert files to Data URIs in JavaScript:
// Using FileReader const fileInput = document.querySelector('input[type="file"]'); const file = fileInput.files[0]; const reader = new FileReader(); reader.onload = function(e) { const dataUri = e.target.result; console.log(dataUri); // data:image/jpeg;base64,/9j/4AAQSkZJRg... }; reader.readAsDataURL(file); // For images in HTML <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA..." alt="Icon" /> // For backgrounds in CSS .icon { background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA...'); }
MIME Types and Base64
Common MIME types for Data URIs:
// Images image/png image/jpeg image/gif image/svg+xml // Fonts font/woff font/woff2 font/ttf // Documents application/pdf text/plain text/html // Audio audio/mpeg audio/wav
Best Practices and Considerations
- Only use for small files (ideally under 5KB)
- Consider caching implications (Data URIs can't be cached separately)
- Base64 encoding increases file size by ~33%
- Use for critical above-the-fold images
- Consider performance impact on mobile devices
- Test browser compatibility for specific use cases
Performance Tips
Selective Usage
Only use Data URIs for small, frequently used resources
Image Optimization
Optimize images before converting to Base64
Caching Strategy
Consider implementing local storage caching for Data URIs
Loading Performance
Balance between Data URIs and traditional resource loading