Using WebP as Background Image with JPG/PNG Fallback
Please Subscribe to our YouTube Channel
WebP is an advanced image format designed specifically for the web, offering excellent compression for both lossless and lossy images. By utilizing WebP, website owners and developers can generate smaller yet more visually appealing images, resulting in improved web performance and faster loading times. However, not all browsers support this format, so it’s important to provide a fallback image for those that don’t.
This article will guide you on how to use WebP images as the background image on your website and how to provide fallback images in JPG or PNG formats for browsers that do not support WebP. We’ll accomplish this using a combination of CSS and JavaScript.
Here’s an example JavaScript code snippet that does this:
In the example below, I am changing the background for <body>
document.addEventListener("DOMContentLoaded", function() {
var img = new Image();
img.onload = function() {
document.body.style.backgroundImage = 'url(' + this.src + ')';
};
img.onerror = function() {
// Fallback for browsers that do not support WebP
document.body.style.backgroundImage = "url('path/to/fallback.png')";
};
img.src = 'path/to/background.webp';
});
This JavaScript code works by creating a new image object and attempting to load the WebP image. If the WebP image successfully loads, it sets this image as the background for both the body
. If there is an error loading the image (which would occur if the browser does not support WebP), it instead sets a PNG image as the background.
Now, let’s break down each section of this code and explain it in detail.
The JavaScript Code Explained
1. Waiting for the Document to Load:
Before we can manipulate elements on a web page, we need to ensure the page’s Document Object Model (DOM) is fully loaded. We achieve this by adding an event listener to the DOMContentLoaded
event. The “DOMContentLoaded” event is triggered once the initial HTML document has finished loading and parsing, regardless of whether stylesheets, images, or subframes have completed loading.
document.addEventListener("DOMContentLoaded", function() {
...
});
2. Creating a New Image Object:
Inside the function, we first create a new image object using var img = new Image();
. This object has properties and methods that allow you to manipulate images on the canvas.
var img = new Image();
3. Setting the Image to Load:
Next, we define what should happen when the image loads using the onload
function. When the image loads successfully, the onload
function sets the WebP image as the background image for the body
element using their style.backgroundImage
properties.
img.onload = function() {
document.body.style.backgroundImage = 'url(' + this.src + ')';
};
4. Providing a Fallback Image:
In the onerror
function, we provide a fallback image for browsers that do not support WebP. If there’s an error loading the WebP image, this function is called, setting the fallback PNG image as the background for the body
element.
img.onerror = function() {
document.body.style.backgroundImage = "url('path/to/fallback.png')";
};
5. Setting the Image Source:
Finally, we set the source of the image object to be the WebP image. This will start the loading process, and depending on the outcome, one of our functions (either onload
or onerror
) will be called.
img.src = 'path/to/background.webp';
This strategy ensures that users with modern browsers can enjoy the benefits of faster-loading WebP images, while those with browsers that do not support WebP will still have a functioning site with a traditional image format as the background.
The Impact of WebP Images on SEO and PageSpeed Score
Along with improving site performance, the use of WebP images can also have a significant impact on your website’s Search Engine Optimization (SEO) and Google PageSpeed Insights score. The reasons for this are interrelated, rooted in how search engines evaluate website performance and user experience.
WebP and SEO
When search engines like Google evaluate a website for SEO, they consider a variety of factors. Among these, website speed is a significant consideration. The rationale is straightforward: fast-loading sites provide a better user experience than slow-loading ones. Given that user experience is an integral part of SEO, improving your site speed can have a direct positive effect on your website’s search engine ranking.
As WebP images typically have smaller file sizes than their PNG or JPEG counterparts for similar quality levels, they can substantially reduce the amount of data that needs to be loaded when a user visits your website. This speedier load time results in a smoother, more enjoyable experience for the user, reducing bounce rates and increasing the time spent on the site — all important factors in SEO.
WebP and Google PageSpeed Insights
Google PageSpeed Insights is a complimentary tool offered by Google, which examines the content of a web page and provides recommendations to enhance its speed. By analyzing various aspects, it suggests optimizations to improve the performance of the page. The analysis is based on a set of metrics known as Core Web Vitals, which are key indicators of user experience on a website. Among these metrics are Largest Contentful Paint (LCP) and Cumulative Layout Shift (CLS), both of which can be significantly impacted by image loading.
As previously noted, WebP images load faster due to their smaller file sizes. This reduced load time can improve your LCP score, which measures how long it takes for the main content on your page to load. A better LCP score means your site users can see and interact with your page more quickly, enhancing their user experience.
Furthermore, because WebP images load more quickly, they can reduce instances of layout shift — a problem that occurs when images or other elements load slowly, causing other parts of the page to move around. This can be annoying for users and lead to accidental clicks. By loading faster and thus reducing layout shift, WebP images can improve your CLS score.
Conclusion
Adopting the WebP image format is not only about offering high-quality images with smaller file sizes but also about providing a better user experience, improving your website’s SEO, and boosting your PageSpeed Insights score. However, remember to provide fallbacks for browsers that do not yet support WebP to ensure you’re not excluding any of your audience. The described approach allows you to achieve these results seamlessly, ensuring a consistent user experience across different browser environments.
Do you need any help with theme customization or webp support? Contact me: me@zoheb.org