Auto Swtich JPG/PNG/GIF Images To WebP Format Using jQuery
File Size: | 337 KB |
---|---|
Views Total: | 2087 |
Last Update: | |
Publish Date: | |
Official Website: | Go to website |
License: | MIT |
One of the biggest issues facing web performance today is that images take up the majority of bandwidth usage and thus, contribute to slower web pages.
WebP is a type of image format developed by Google, that takes up less disk space and network bandwidth, it's also better supported by all major browsers like Chrome, Opera, etc.
But unless you're already serving your images in this format, visitors visiting your site have no access to WebP images. This plugin was born to help you replace all existing images (PNG/JPG/GIF) with WebP images using a little bit of JavaScript (jQuery Script). Have fun.
It's worth noting that this plugin only works with images already embedded on old web pages. If you embed new webp images in new web pages, please use the following HTML code:
<picture id="picture"> <source srcset="1.webp" type="image/webp"> <source srcset="1.jpg" type="image/jpeg"> <img loading="lazy" src="1.jpg" alt="Alt Text!"> </picture>
How to use it:
1. Just include the main script after the latest jQuery library and the plugin will take care of the reset.
<script src="/path/to/cdn/jquery.slim.min.js"></script> <script src="js/main.js"></script>
2. Modify the main JavaScript to add more browser support.
(function () { // Check if Browser is Chrome or Opera var isChromium = window.chrome; var isOpera = window.opera; if(isChromium || isOpera){ // Get All Imgages and replace their extension - jpg/png/gif - to new img format WebP var getAnchors = $("img"); for(var i=0; i < getAnchors.length; i++){ getAnchors.attr("src",getAnchors[i].src.substr(0,getAnchors[i].src.lastIndexOf(".")) + ".webp"); } if(isChromium){ console.log("Your Browser is <b>Chrome</b>, script load WebP Images"); } else{ console.log("Your Browser is <b>Opera</b>, script load WebP Images"); } } else{ console.log("Your Browser is not <b>Chrome/Opera</b>, script load default PNG Images"); } })();
This awesome jQuery plugin is developed by TTeRzY. For more Advanced Usages, please check the demo page or visit the official website.