The road of WebP picture practice

Source: Internet
Author: User
Tags webp css preprocessor

We're going to talk about WEBP from three Parts.

    1. What is WEBP and what is it for?
    2. The usual methods of using WEBP and their pros and cons.
    3. How we use the WEBP.

PS: if it is a friend who has a certain understanding of webp, it is suggested to look directly at the third part. Because it is the road to our practice, so the third chapter to speak More.

one, What is webp, what is it used for?

WEBP is Google's introduction of a picture format, its advantage is the same picture quality, volume than jpg, png these less than 25%.

We all know that the mobile Internet era, page size and user retention is closely related, faster loading of the page to allow more users to focus on your content, and the picture has always been the bulk of the page volume, take our activity page, the picture occupies more than 80% of the page size. So the use of WEBP words, can instantly make the page size down 1/4, have to say is a very cost-effective optimization point.

of course, It is not without shortcomings, the browser for the WEBP decoding speed relative to the JPG will be slower, but this and volume reduction resulting in performance improvements, can be Ignored.

So since WEBP is so good, why not use it in a wide range? In the final analysis, WEBP is Google's launch, The main browser is only Chrome and Android Support. But iOS is also fast support, looking forward to ing^ ^. The current compatibility of WEBP can be found on the Caniuse.

Ii. the conventional methods of using WEBP and their merits and demerits

first, We need a tool to turn the image into Webp format, where we can use Google's official tools to Link.

After this is installed, your console has a CWEBP command. Running cwebp-h, The successful display of the help information means that the installation is Ready.

With this tool you can generate WEBP pictures, after the WEBP picture, then how to use, there are two common scenarios.

Scenario One: server-side Processing

This is the most the most worry about the method, the browser supports the WEBP image when sending a request to the server, will be in the request header accept the IMAGE/WEBP. The server can then decide whether to return the WEBP image based on whether it contains this header Information.

This method only needs to do some operation in the Web server, is very simple and convenient.

however, The disadvantage of this scheme is also obvious, first detection through the request, some devices may be not accurate. second, now the image and other static resources will be placed on the CDN server, then at this level plus Judge WEBP logic is a bit troublesome.

Scenario Two: front-end detection support WEBP and then request the appropriate format of the picture

The advantage of this method is that it is very safe to know whether the User's browser supports WEBP through the feature check, and the disadvantage is that the logic of detecting WEBP is added to the business Code.

The usual practice is to perform a section of WEBP detection before the page load, to determine whether the browser supports the WEBP format, the results into a cookie, when loading the picture, if it is lazy loading pictures, then according to whether support WEBP to process the picture path is good, if not lazy loading of the picture, You can render the template on the backend, depending on whether we set the cookie to support WEBP.

These are now compatible with WEBP when the page is introduced into the image via an IMG Tag. If it is a CSS introduced in the picture, the scheme is generally built two sets of css, and then in the Back-end template according to the cookie to determine which set of use, or in the CSS through the selector, such as for the browser support webp, we add webps class name on the HTML root node, Then for the introduction of the picture, through this class name to do the selector priority coverage, specific we look at the third part of the code in Detail.

third, How we use the WEBP

Here's the point, and here's what we do for WEBP.

First of all, Let's talk about our present situation, our pictures have two kinds of storage methods. For some dynamic pictures, such as the product map, these are stored on our image server, this server supports WEBP format, only need to add parameter t=5 after the picture path to get the WEBP format picture.

For the introduction of CSS background map, we stored in a cdn, this part of the trouble, do not support the generation of WEBP pictures, so you can only send a copy of the corresponding WEBP pictures up.

And due to various reasons and limitations, we can not adopt the above-mentioned Server-side processing scheme, so we can only use the front-end code processing METHOD. I think some companies do not use WEBP may also be these reasons, because the pure front-end processing is really quite round.

Combined with our business situation, because it is the operating activity page, the background and product charts are basically half of each, and even more background, so we need to put the CSS introduced in the picture and the IMG tag introduced by the image are made WEBP compatible T T.

For the IMG tag introduced by the image, because our image server support webp, and our product map is mostly lazy loading, then it is simple, directly modify our lazy loading plug-in can be implemented, in the replacement of the real picture path when the decision whether to support webp, and then replace the corresponding path.

For the introduction of CSS images, we have to take advantage of CSS overrides, for example, if the browser supports webp, then we add webps class name to the HTML root node. so, for example, We write

span {background-image:url (a.jpg)}

, write it Again.

. webps span {background-image:url (a.jpg.webp)}

In this way, devices that support the WEBP format will automatically load WEBP images.

of course, You're going to have two questions Here.

One is each time you write the code to add. webps it's too much work to write Again.

The second is the corresponding WEBP picture of each picture is where to come? Do you need to build it yourself?

In view of these two problems, we found the corresponding solution, for the problem we use the CSS preprocessor to generate the corresponding WEBP Code.

Problem two we used Nodejs to write a script to monitor the image folder, when the image is added, modified, deleted, it will generate or delete the corresponding WEBP Image.

Having said so much, let's take a look at the code Implementation.

first, we need to include a WEBP check code in the first part of the Page. The purpose of this code is to check whether the current browser supports webp, and if so, add the webps class name to the HTML root node for use by Css. And a cookie named webps with a value of a is recorded in the cookie for a period of one year. In this way, you can then use the WEBP class name in the CSS to do compatible processing, the IMG tag introduced by the image can be used to know whether the browser supports webp, and then do the corresponding processing, the backend can also be informed by the cookie device to WEBP support situation to do some differential rendering.

This code is as follows, it should be noted that this code to be loaded before the introduction of css, the meaning of the code can be directly read the Comments.

;(function (doc){//to the HTML root node plus the Webps class name function Addroottag () {doc.documentElement.className + = "webps"; }//determine If there is a webps=a this cookie if (!/(^|;\ S?) Webps=a/.test (document.cookie)){var image = new Image (); When the picture is loaded, the operation image.onload = function () {//the picture is loaded successfully and the width is 1, then the WEBP is supported because this base64 is WEBP format. If not supported will trigger the Image.error method if (image.width = = 1) {//html root node Add class and Embed cookie Addroo                Ttag (); Document.cookie = "webps=a; max-age=31536000;            Domain=58.com "; }        }; A picture of WEBP that supports Alpha transparency, using base64 encoding image.src = ' Data:image/webp;base64,uklgrkoaaabxrujqvla4waoaaaaqaaaaaaaaaaaaqux    qsawaaaarbxar/q9erp8daabwudgggaaaabqbaj0bkgeaaqaaap4aaa3aap7mtqaaaa== '; } else{Addroottag (); }} (document)); 

Then we deal with the IMG tag introduced by the image, because our image server support webp, and the image introduced by IMG is loaded by lazy loading, so this part of our processing is relatively simple, when lazy loading replace the real path, the cookie is determined whether there is webps= A This cookie to determine the URL of the loaded Picture.

of course, If you are not lazy loading the introduction of the picture, then can be in the Back-end rendering, through the cookie we write to determine whether to use the WEBP image, is also very convenient. This part of the code is relatively simple, it is not posted Out.

Then the CSS introduced in the picture, because the CSS does not support logic, we can now take advantage of the HTML root node of The. webps class Name. We used this mixin in scss to load Images. The code action can be viewed under Comments.

 /*   Use this function to introduce a picture, for example: #wrapper {@include BG (' .. /img/sample.jpg ')} This code is compiled and generates the following two lines of code #wrapper {background-image:url ('. /img/sample.jpg '); }. webp #wrapper {background-image:url ('. /IMG/SAMPLE.JPG.WEBP ');  */  @mixin BG ($url)  { Background-image :  URL ($url) ;  @at-root (with : ; Span style= "color: #ff0000;"    > {background-image :  URL ($url + '. webp ') ; }     

If you are using less, you can do the same with the Code BELOW.

{    background-image: url (@url);     . webps & {        background-image: URL (' @{url}. webp ');}    }  

The last is how to generate WEBP Pictures. For CSS introduced in the picture, because it is placed on the cdn, we need to generate the corresponding WEBP Image.

How to do the development of the time automatically supporting the generation of WEBP pictures, we began to think of our build tool to write a plugin to achieve the compile time to generate WEBP pictures, however, we found that because the various projects using the build tool may be different, such as fis3, Webpack and our own development of build tools , too much, for each development cost is too high. So we decided to use Nodejs to write a small script, the role is to monitor our image folder, at any time to generate matching WEBP pictures, when the image has been added, modified, deleted, it will add, modify, delete the corresponding WEBP Image.

The tool code is as Follows. The default listener images folder, after NPM install dependency, the direct node webp-monitor.js can Both. Of course, The premise is that you follow the second part of the official Google Webp generation tool, or simply say that your terminal needs to have CWEBP this command.

/*webp image Generation run: npm install && NPM Start program relies on Google official WEBP conversion tool CWEBP Mac installation of Brew install WEBP Windows can go to google official download after the installation is complete run cwebp-h if the use of help shows that the installation was successful*/Const Process= Require (' child_process '); Const FS= Require (' FS '); Const Chokidar= Require (' Chokidar '); Const Log=console.log.bind (console); Const Ignorefiles= /(^\.. +)| (.+[\/\\]\.. +)| (. +?\.webp$)/;//ignores Files. beginning and end Of. WEBPlet Quality= 75;//WEBP image quality, defaultLet Imgdir = ' images ';//Default picture Folder//get the file name of the corresponding WEBP format, the default is filename plus. webpfunctiongetwebpimgname (path) {return' ${PATH}.WEBP ';}//get the shell commandfunctiongetshellcmd (path) {return' Cwebp-q ${quality} ${path}-o ${getwebpimgname (path)} ';}//Monitoring FoldervarWatcher =chokidar.watch (imgdir, {ignored:path=> {        returnignorefiles.test (path); }, persistent:true //Maintain listening status});//listen for events that add, modify, and delete filesWatcher.on (' all ', (event, Path) => {    Switch(event) { case' Add ':         case' Change ': generatewebpimg (path, status)=> {log (' Generate picture ' + getwebpimgname (path) +status);            });  break;  case' Unlink ': deletewebpimg (getwebpimgname (path), (status)=> {log (' Delete picture ' + getwebpimgname (path) +status);            });  break; default:             break; }}); Log (' biubiubiu~~~ monitoring has been started ');functiongeneratewebpimg (path, cb) {process.exec (getshellcmd (path), Err=> {        if(err!==NULL) {CB (Failed); Log (' Please run the cwebp-h command first to check if CWEBP is installed Ok. ‘) Log (err); } Else{CB (Success); }    });}functiondeletewebpimg (path, cb) {fs.unlink (path, (err)=> {        if(err) {CB (Failed); Log (err)}Else{CB (Success);    }; });} 

At this point, we have implemented the use of WEBP images in our Projects.

The road of WebP picture practice

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.