Images play a significant role in the overall page weight of many websites, significantly impacting performance. Employing optimisation techniques, such as lazy loading, can help alleviate this issue. However, the absence of image placeholders can create confusion for users, giving the impression of a page error. Incorporating image placeholders are a great way to enhance the user experience by providing valuable feedback during the loading process.
I recently implemented this technique in a project using Next.js and WordPress. Given the website’s strong emphasis on images, this approach was necessary to dynamically load server-side images without compromising the site’s visual appeal.
LEVERAGING THE NEXT.JS DEFAULT BLUR PLACEHOLDER
The Nextjs image component offers numerous features for automatic image optimisation, including an optional blur placeholder. To implement this...
- Set the placeholder prop to “blur”
- For dynamic images, provide the blurDataUrl prop to enable pre-rendering of a base64 blurred version of the image on the server.
<Image
src="image.url"
alt="image.alt"
height={500}
width={500}
placeholder="blur"
blurDataUrl="image.base64"
/>
For dynamic images, the Next.js documentation suggests using the Plaiceholder library for generating base64 blur data. As my specified use case involved rendering images within a client-side component (Plaiceholder runs in the Node.js environment), I chose to explore alternative approaches, instead opting to send this data within the WordPress API response.
GENERATING THE BLUR DATA
To produce the blur data, images need to undergo encoding as a base64 string. Base64 serves as a binary-to-text encoding scheme, transforming binary data into a readable text format.
I was able to achieve this using the following PHP code snippet...
'base64' => 'data:image/' . $image_type . ';base64,' . base64_encode(file_get_contents($image_thumbnail))
To transmit this data to the frontend, I adapted the WordPress REST API response to incorporate the respective base64 string for each requested image.
THE RESULT
By utilising the Next.js image component’s built-in blur prop, I was able to implement a blur placeholder to improve the website’s user experience by reducing the perceived loading time of images.