Image Placeholders
Choosing SVG or PNG Placeholder Images: Avoid Layout Shifts and Scaling Issues
Learn when to use SVG or PNG placeholders to avoid pixelation and Cumulative Layout Shift (CLS) by matching API dimensions to production assets.
The RoutexAPI TeamUpdated August 18, 20264 min read
Choose SVG when building fluid, responsive grids and PNG when targeting legacy environments or mobile apps that require raster assets. The choice between these formats determines whether your placeholders scale cleanly across different screen densities or remain compatible with restrictive image renderers.
SVG for responsive layouts vs PNG for legacy compatibility
SVG placeholders are the correct choice for modern web applications. Because they are vector-based, they scale without pixelation, making them ideal for responsive layouts where an image might occupy 100% of a container's width on mobile but only 33% on desktop. Using the /svg/{width}/{height} endpoint ensures that the resulting asset remains crisp regardless of the browser's zoom level or the device's pixel density.
PNG placeholders, requested via /{width}/{height}, are raster images. While they are widely compatible across almost every legacy browser and mobile environment, they suffer from blurriness if stretched beyond their requested dimensions. Use PNGs for fixed-size components, such as profile avatars in a legacy CMS or specific image previews in mobile apps where SVG support may be inconsistent.
Match placeholder dimensions to production assets to prevent layout shift
Cumulative Layout Shift (CLS) occurs when the browser renders a page and then shifts content as images load. If you use a placeholder that is 300x300 but the final production image is 600x400, the browser will reflow the entire page once the production asset arrives.
To prevent this, you must set the width and height parameters in your API request to match the final intended dimensions of the production asset.
The Calculation Method:
- Identify the final aspect ratio of your production asset (e.g., 16:9).
- Determine the maximum width the image will occupy in the layout.
- Calculate the height:
(Width / 16) * 9. - Pass these exact integers to the API endpoint.
If you omit the text parameter, the API automatically displays these dimensions (e.g., "640x480") on the image. This provides a visual sanity check for developers to ensure the placeholder matches the intended slot in the UI.
Handle invalid parameters and authentication errors early
The API will return specific HTTP status codes when a request fails. Handling these early in your request pipeline prevents your UI from attempting to render broken image links.
401 Unauthorized
This is the most common failure mode. It occurs when the x-service-api-key header is missing or invalid. Ensure your API key is passed in the header, not as a query parameter.
400 Bad Request This occurs when parameters are malformed. Common causes include:
- Non-integer dimensions: Passing a float or string to the
{width}or{height}path segments. - Invalid HEX codes: Using a HEX value that is not exactly 6 digits for the
backgroundorcolorparameters.
Validation Strategy: Before making the request, validate your inputs on the client or server side:
- Use a regex like
/^[0-9A-Fa-f]{6}$/to verify HEX codes. - Ensure dimensions are cast to integers.
Implementing SVG and PNG placeholders in Node and Python
Avoid storing these images as static files in your repository. Instead, request them on demand and embed the URL directly into your HTML.
Node.js Implementation
This example uses axios to verify the image exists before passing the URL to a frontend template.
const axios = require('axios');
async function getPlaceholderUrl(width, height, label = 'Placeholder') {
const apiKey = 'YOUR_API_KEY';
const baseUrl = 'https://routexapi.com'; // Replace with actual base URL
const bg = 'CCCCCC';
const textColor = '333333';
// Constructing an SVG request for responsiveness
const url = `${baseUrl}/svg/${width}/${height}?background=${bg}&color=${textColor}&text=${encodeURIComponent(label)}`;
try {
const response = await axios.head(url, {
headers: { 'x-service-api-key': apiKey }
});
if (response.status === 200) {
return url;
}
} catch (error) {
console.error('Placeholder generation failed:', error.response?.status);
}
return '/fallback-image.png';
}
// Usage
getPlaceholderUrl(800, 600, 'Hero Banner').then(console.log);
Python Implementation
This example demonstrates how to generate a PNG placeholder URL for an e-commerce product catalog.
import urllib.parse
def generate_placeholder_url(width, height, text="Product Image"):
base_url = "https://routexapi.com" # Replace with actual base URL
api_key = "YOUR_API_KEY"
# Parameters for a PNG placeholder
params = {
"background": "F5F5F5",
"color": "333333",
"text": text
}
query_string = urllib.parse.urlencode(params)
full_url = f"{base_url}/{width}/{height}?{query_string}"
# In a real scenario, you would include the x-service-api-key
# in the HTTP header of the request that fetches this URL.
return full_url
# Usage
print(generate_placeholder_url(800, 800))
Fallback strategies for production stability
Depending on your infrastructure, relying on an external API for critical UI elements introduces a point of failure. If the API is unreachable or returns an error, your layout could collapse or display a broken image icon.
Local Fallback Cache:
Keep a small set of generic, locally hosted placeholders (e.g., fallback-400x400.png). If your application detects a non-200 response from the API, the application should switch to the local asset. This ensures that your UI remains functional and your automated tests do not fail.
Request Batching and Caching: In development environments, avoid calling the API inside a loop that renders a large gallery. Instead, use a single placeholder size for all items in a grid and let the browser cache the response. This reduces the number of network calls and speeds up page load times during the prototyping phase.
Graceful Degradation in CSS:
Combine the API placeholders with CSS background-color as a tertiary fallback. By setting a background color on the image container that matches the background parameter sent to the API, you ensure that even if the image fails to load entirely, the user sees a colored block of the correct dimensions rather than a white void.
By combining SVG for responsiveness, matching production dimensions to eliminate CLS, and implementing robust fallback logic, you can build a prototype that behaves like a production environment without the overhead of managing static image assets.
Try it on RoutexAPI
Skip the setup
Would rather not run and maintain this yourself? These APIs on RoutexAPI do the same job behind one key.
