What javascript code can I use to replace all html images with webp extension to png when the browser is Safari?

I converted all the images of the site to the format .webp . However, the Safari browser (Apple) still does not recognize it.

So I kept on the server all the images also in .png . I would like to insert a javascript code that gives a .replace() in all images of the document HTML when the browser is Safari, replacing .webp by .png .

Below is an example:

<!-- Link para os navegadores Chrome, Edge e Firefox: -->
<img class="imagemsafari" src="images/marcas/Ecommerce-life-detox.webp" alt="Life Detox">

<!-- Link par ao navegador Safari: -->
<img class="imagemsafari" src="images/marcas/Ecommerce-life-detox.png" alt="Life Detox">

So far the only option that I found it using the code below. Which unfortunately only changes a id . Follows below:

<script>
    if ( navigator.userAgent.indexOf("Safari") != -1 ) {
        var str = document.getElementById("imagemsafari").src; 
        var res = str.replace(/webp/g, "png");
        document.getElementById("imagemsafari").src = res;
    }
</script>

Could I explain?

Author: Lauro Moraes, 2019-06-25

3 answers

You don't need javascript for this!

You can use the tag picture and place the two images (webp and png), so if the first image fails to load, the browser itself understands that it should look for the second and so on.

Using the picture element

Follows a example of using the picture element:

<picture>
  <source srcset="img/awesomeWebPImage.webp" type="image/webp">
  <source srcset="img/creakyOldJPEG.jpg" type="image/jpeg"> 
  <img src="img/creakyOldJPEG.jpg" alt="Alt Text!">
</picture>

Note that it was necessary to pass 2 elements source and one element img into this example. In this case, as they are two uri and different image types, we define this with the first 2 source, in the order in which we want it to be loaded and leave a tag img that the browser will "inject" the first source that works.

 0
Author: Paulo Souza, 2019-06-25 10:17:31

You can use tag picture:

<picture>
  <source srcset="path/imagem.webp" type="image/webp">
  <img src="path/imagem.png">
</picture>

Or

You can put an attribute on your images like this: <img data-img ... /> and do something like this:

window.onload = function() {
    if (navigator.userAgent.indexOf("Safari") != -1) { 
        var sources = document.querySelectorAll("[data-img]"); 
        for (var i in sources) {
            var url = sources[i];
            if (url.src.indexOf('.webp') !== -1) {
                url.src = url.src.replace(/\.webp/gim, ".png");  
            }
        }
    }
}

Or you can put a rule if an interpretation error occurs in the image like this:

<img onerror="this.src='path/arquivo-alternativo.png'" src="path/arquivo-alternativo.webp">

Or you can create a folder for safari and point the path of your images:

 var dir = '/images/'
 if (navigator.userAgent.indexOf("Safari") != -1) { 
     dir = '/safari-images/';
 }
 0
Author: Ivan Ferrer, 2019-06-25 10:53:07

Certainly using the elements <picture> and <source> is the most canonical method since modern browsers already support it and decide properly which format to use.

However, using JavaScript is a good option if you want to avoid having to manually modify all entries in all documents on your site.

Once you already have a duplicate of the formats you should:

  • 1: check format support (if not supported)
  • 2: Search all element References <img>
  • 3: iterate over this list and check if the src contains ".webp '
  • 4: modify all attributes .src found

Something like this:

// no topo do seu script checar se o navegador supoorta o formato
var BrowserSupportWebpCheck = document.createElement('canvas').toDataURL('image/webp').indexOf('data:image/webp') === 0

// se o navegador não suportar o formato ".webp"
if ( !BrowserSupportWebpCheck ) {
    // buscar todos os elementos "<img>"
    var images = document.querySelectorAll('img')
    // ES5 usa "forEach" ... suporta IE 9 em diante
    images.forEach((item, index, array) => {
        if ( item.src.indexOf('.webp') !== -1 ) {
            // substituir o "src" do elemento
            item.src = item.src.replace('.webp', '.png')
            // apenas para este exemplo, mostrar
            console.log(item.src)
        }
    })
}
<img src="path/to/image.webp">
<img src="path/to/image.webp">
<img src="path/to/image.webp">
<img src="path/to/image.webp">
<img src="path/to/image.webp">
<img src="path/to/image.webp">
<img src="path/to/image.webp">
<img src="path/to/image.webp">
<img src="path/to/image.webp">

The code snippet above will "print" in the console all attributes src found and modified to .png ... of course, it will only do so in fact if the Browse does not support the format .webp

It should also be noted that it is not only Safari that does not support the format.webp and the element <picture>, old browsers and some "mobile" also do not support.


Support references:

 0
Author: Lauro Moraes, 2019-06-25 11:49:45