简体   繁体   中英

How to load a webp image into a `new Image()` via JavaScript in Safari

I just switched to webp images and noticed that they're not working. I'm using a lazy loading plugin to handle loading these images. This is where the problem is coming in. I'm hoping to be able to submit a pull request to fix this... if it's possible.

Here is an example that demonstrates a success and a failure for two different image formats:

https://codepen.io/corylogan/pen/OJJMERo?editors=1010

Here's the code for posterity

const loadImageAsync = (item) => {
  let image = new Image()
  console.log(item)
  image.src = item
  image.onload = function () {
    console.log('successful onload')
  }

  image.onerror = function (e) {
    console.log('got an error')
    console.log(e)
  }
}

loadImageAsync('https://upload.wikimedia.org/wikipedia/commons/a/a5/Red_Kitten_01.jpg')
loadImageAsync('https://s3.amazonaws.com/road-trip-blog/1c9fe9f0-4e9e-3604-9b77-e35d7ecfc40f-w2100.webp')

In chrome both images will report success. In Safari and Mobile Chrome on iOS the webp fails with an error to the effect of: {"isTrusted":true} .

The error is not very helpful. But I think I might have a clue when I look at the headers sent from Chrome and Safari for the corresponding request:

Safari

Request
GET /road-trip-blog/1c9fe9f0-4e9e-3604-9b77-e35d7ecfc40f-w2100.webp HTTP/1.1
Accept: image/png,image/svg+xml,image/*;q=0.8,video/*;q=0.8,*/*;q=0.5
Pragma: no-cache
Referer: https://cdpn.io/
Cache-Control: no-cache
Host: s3.amazonaws.com
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.2 Safari/605.1.15
Accept-Language: en-us
Accept-Encoding: br, gzip, deflate
Connection: keep-alive

Chrome

Provisional headers are shown
Referer: https://cdpn.io/
Sec-Fetch-Mode: no-cors
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36

Guesses

Could it be something to do with the Sec-Fetch-Mode in chrome, or the Accept header in Safari?

I can't think of much else right now. Any ideas?

I feel silly: Webp is not supported on iOS or in Safari. It just won't work. https://caniuse.com/#feat=webp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM