Dynamic SVG Image Placeholders In JavaScript – placeholder.js

Category: Image | August 30, 2024
Authormeenaviyal
Last UpdateAugust 30, 2024
LicenseMIT
Views69 views
Dynamic SVG Image Placeholders In JavaScript – placeholder.js

placeholder.js is a lightweight JavaScript library for generating SVG-based placeholder images directly within your web pages.

When the page loads, it automatically replaces the specified <img> elements with vibrant, colorful, randomly generated SVG placeholders, including random shapes and Unicode emoticons.

This approach offers several benefits:

  • Faster prototyping: You can quickly populate your layouts with visually engaging placeholders.
  • Reduced reliance on external resources: No need to search for or manage external image placeholder services.
  • Visual consistency: Maintain a consistent look and feel throughout your project even with placeholder content.

How to use it:

1. Download the SVG Placeholder library and include the placeholder.js script in your HTML file:

<script src="placeholder.js"></script>

2. Insert <img> elements where you want your placeholders to appear. Assign them classes following the pattern placeholder-[width]-[height], substituting the desired width and height in pixels. For instance:

<img class="placeholder-400-300" alt="400x300 Image Placeholder">
<img class="placeholder-1080-720" alt="1080x720 Image Placeholder">
<img class="placeholder-320-160" alt="320x160 Image Placeholder">

3. That’s it. The library automatically replaces these images with SVG placeholders when the page loads.

How it works:

The library functions by first selecting all <img> elements with classes starting with placeholder-.

It then extracts the width and height values from the class name using a regular expression. For each placeholder:

  • It creates an SVG element with the specified dimensions.
  • It adds a randomly colored background rectangle.
  • It generates a random number of shapes (circles, rectangles, or text elements displaying emoticons) and positions them randomly within the SVG.
  • It adds a text element displaying the dimensions in the center of the SVG for easy identification.

Finally, it converts the SVG to a data URI and sets it as the src attribute of the <img> element, effectively replacing the placeholder with the generated SVG.

You Might Be Interested In:


Leave a Reply