Course contentsShow
← JavaScript
Lesson 2359 of 2,72348. Working with Binary DataFree lesson

Data URLs with Base64

Create data: URLs by prefixing Base64-encoded content with media type, enabling inline images and fonts.

Data URLs with Base64

You'll learn how to embed binary data directly into your HTML or CSS by creating data URLs with Base64 encoding.

What is a Data URL?

A data URL is a special type of URL that contains the actual file content inline, rather than pointing to an external resource. Think of it like quoting an entire book in your conversation instead of just naming the book's location on a shelf.

The format follows a specific pattern:

data:[mediaType];base64,[base64EncodedData]

Creating Data URLs

When you Base64-encode binary data (like images or fonts), you can prefix it with the media type to create a complete data URL that browsers understand:

// Suppose you have binary data as a Uint8Array
const binaryData = new Uint8Array([137, 80, 78, 71, /* ... PNG bytes */]);

// Convert to Base64 (using techniques from previous lessons)
const base64String = btoa(
  String.fromCharCode(...binaryData)
);

// Create the data URL with proper media type
const dataUrl = `data:image/png;base64,${base64String}`;

// Now use it directly in an img tag
// <img src="data:image/png;base64,iVBORw0KG..." />

Common Media Types

  • Images: data:image/png;base64,... or data:image/jpeg;base64,...
  • Fonts: data:font/woff2;base64,...
  • SVG: data:image/svg+xml;base64,...

Data URLs eliminate separate HTTP requests, making them useful for small resources you want to bundle directly into your HTML or CSS. They're particularly handy for icons, small images, or web fonts.

Key Takeaway: Data URLs let you embed file content directly by prefixing Base64-encoded data with data:[mediaType];base64,, enabling inline images and fonts without external requests.