Optimization Practice of picture resources in e-commerce platform

yun_ Little dream 2021-09-15 10:21:53

Picture rendering optimization

I've talked about pictures many times before . Several schemes are also given . These are undoubtedly feasible and convenient in practical use :

  1. loading
  2. connection API + promise.all() Loading images asynchronously
  3. Skeleton screen
  4. Lazy loading + Occupation map

But in the e-commerce scenario , The first option is not possible : We can't give up the normal presentation of the whole content to users for one picture .( Especially this picture is just a background picture )

The second scheme works wonders on the home page , But I think there are too many restrictions —— If for “ Universal ” In terms of the plan , The skeleton screen seems to be more suitable for medium and large-scale projects . The scenario proposed at that time was : There will be a large rotating picture on the front page of our experimental system , But its function is only to show and publicize . Obviously , This rotating picture doesn't need all the pictures to be displayed , But if you let it go , When the network situation is slightly worse, there will be blank or even flash white problems . That's not good. ! So use connection API Check the current network situation to determine whether to display a rotating picture or a picture .

The last scheme should be commonly used now . The occupied bitmap can also be replaced with a fixed width and height 、 With background color div, Reduce one request for pictures ( I used to do this on the homepage of where to go ). But its drawback is : If the picture is too big , For a long period of time loading It also makes users feel irritable !

It's impossible not to deal with it . A long white screen or flashing white is expected to drive the product crazy ...


CSS spirte It's a good thing , It can greatly reduce http expenses .spirte + prefetch The combination of can optimize http Let it be loaded early while requesting :

<link rel="prefetch" href="xxx" />
 Copy code 

prefetch It's for the browser “ Hint ”: Some resources may be needed in the future , But it's up to the browser to decide whether and when to load these resources . It has a lower priority .

spirte The principle is to put all the pictures needed for the whole page into one picture , adopt transform Move to where you need to show . But again : If there are many pictures that are too large , It will make the loading of Sprite chart extremely difficult , This brings a bad user experience .

Lazy loading

As soon as you enter the web page, a large number of image resources will be loaded , This will indirectly affect the loading of the page , Increase white screen loading time , Impact on user experience . therefore , Our appeal is that images not in the visualization window are not really loaded , Minimize the waste of local bandwidth and the amount of requested resources .

The advantage of lazy loading is obvious :

  • Reduce bandwidth resource consumption , Reduce unnecessary resource loading consumption .
  • Prevent resource loading blocking caused by concurrent loading of picture resources , Thus reducing the white screen time .

Implement simple lazy loading

There are two ways to do it :

  1. adopt scroll Event to monitor the window scrolling area . This method has good compatibility , Most browsers and WebView Are compatible and support .
  2. adopt IntersectionObserver API Observe DOM Whether it appears in the window , The advantage of this method is that it is easy to call , Only some mobile terminals are compatible, which is not as good as the previous method .

Both forms are observing the current DOM Whether it appears in the visual window , If it happens, it will data-src The picture address in is assigned to src, Then start loading the current picture .

The author has studied Preloading and lazy loading ( Click to view the article ), It encapsulates a function that can be called . But that's by listening scroll The way . in fact , Browser provided IntersectionObserver API It should be more convenient :

const root = Get parent element ;
const options = {
root: root,
// Here is an array that can specify multiple scales, similar to [0.25, 0.5, 0.75, 1]
threshold: [0],// The rendezvous 
rootMargin:"0px"// Shrink and expand the viewport 
const lazyIntersection = new IntersectionObserver(entires => {
// entires An array object for the listening nodes 
entires.forEach((item,index) => {
// console.log(item.target, item.isIntersecting? ' so ': ' invisible ')
// isIntersecting Is whether the cross region of the current listening element is within the threshold specified by the visual region. It returns a Boolean value 
if(item.isIntersecting) {
console.log(' so ')
item.target.src = item.target.getAttribute('data-src')
// Here, the observation stops after the resource is loaded 
// console.log(item)
}, options)
let data = Array.from(document.querySelectorAll('img'))
data.forEach(item => {
// observe Used to observe specified DOM node 
 Copy code 

Large picture rendering optimization

You may have seen a picture like this : 1231 Common image loading method and later proposed jpg Progressive loading png Staggered loading It's nothing compared to . in fact , Progressive loading is more common in practical use —— Recommended by the author jpeg Progressive loading of format : You don't have to download the picture completely , You can see the content of the picture . Yes, it is a loading method from fuzzy to clear .

See a lot of articles with JS Imitate this way to load pictures . however ... You put the picture http Convert consumption to single thread js Blocking . The result is that the user sees the page / But the interaction time is getting longer . That's good ?

use photoshop There is a... When generating pictures “ Stored as web Format used ”, then , The continuous check is progressive JPEG Picture. : Bear in mind ! You need to check the conversion to sRGB Options , In some browsers , The image is set to CMYK There will be some problems ! FireWorks And other image software also have similar output settings .

Advantages and disadvantages of progressive pictures

  1. Progressive pictures are sized and framed at the beginning , Not like a basic picture , Backflow due to unset size —— Improved rendering performance ;
  2. Progressive pictures also have shortcomings , Just eat CPU Eat memory .

Long graph rendering optimization

In the e-commerce scene , The hardest thing is actually the product details page , Detailed descriptions of some commodities may be configured here . Not only the quality of the picture will be higher , At the same time, the picture will be very long . So obviously , We can't say that we can get the picture directly and display it on the page , If the user's network speed is slow , A long white note will appear directly on the page , Or an error diagram of loading failure . These are obviously not the results we want .

What shall I do? ? The author studied our picture processing tool : When you click on the big picture , You will find that only part of the picture is displayed , Or show only the top small part of the content in the large area for the first time .

According to this idea , We can do corresponding tangent optimization , Divide a long graph into multiple blocks of equal scale , To do a batch render tuning , Reduce the pressure of rendering long images in a single time .

This step is obviously handled by the back-end —— take Node Come on , You can download gm1 or ImageMagic2

npm install --save gm
 Copy code 

gm Functions for clipping are provided in :

gm("img.png").crop(width, height, x, y)
 Copy code 

ImageMagic More powerful , Not only can you cut pictures , And support Picture format conversion and Image recognition And so on !

After processing, it can be stored in a special directory , Then listen to scroll or IntersectionObserver API Keep requesting... As users decline “ Next paragraph ” picture .

Picture exception handling

There are two kinds of anomalies in the picture : Load exception and Rendering exception .

Load exception

Loading exception means “ The picture request failed due to various reasons ”. Because pictures belong to resources , An exception to a resource will trigger a Event Interface error event , these error Events don't bubble up to window, But can be caught . and window.onerror Cannot monitor capture . But it can be addEventListener Capture :

// picture 、script、css Load error , Can be captured 
window.addEventListener('error', (error) => {
console.log(' Exception caught :', error);
}, true)
<img src="https://yun.tuia.cn/image/kkk.png"> <script src="https://yun.tuia.cn/foundnull.js"></script> <link href="https://yun.tuia.cn/foundnull.css" rel="stylesheet"/> // new Image error , Unable to capture <script> window.addEventListener('error', (error) => { console.log(' Exception caught :', error); }, true) </script> <script> new Image().src = 'https://yun.tuia.cn/image/lll.png' </script> // fetch error , Unable to capture <script> window.addEventListener('error', (error) => { console.log(' Exception caught :', error); }, true) </script> <script> fetch('https://tuia.cn/test') </script>  Copy code 

Rendering exception

Rendering exception is actually what we call “ I can't see the picture on the page 、 Display blank ”. What we usually need to do is “ Degraded processing ” —— For example, give a failure prompt , Or give a degraded picture ( For example, use z-index Blessed background、 The picture under the blessing of pseudo elements /SVG).

Bear in mind ! If you use loading Do load optimization , Don't let loading Always exist !

  1. gm Official website :www.graphicsmagick.org/
  2. ImageMagic Official website :imagemagick.org/
Please bring the original link to reprint ,thank
Similar articles