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

Asked

Viewed 198 times

0

I converted all images from the site to the format .webp. However, the Safari (Apple) browser doesn’t recognize it yet.

Therefore, I kept all images on the server as well .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 for .png.

Below 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 I found is using the code below. Which unfortunately only changes one id. Goes 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>

I was able to explain?

  • It is not only Safari that does not support .webp ... you should check format support instead of browser

3 answers

0

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

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

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

  • 1: check format support (if not supported)
  • 2: find all element references <img>
  • 3: iterate over this list and check whether 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" on the console all attributes src found and modified for .png ... of course, it will only do it 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

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 error when being loaded, the browser itself understands that it should look for the second and so on.

Using the picture element

Follows a example use of 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 an element img in this example. In this case, since there are two different Ri and image types, we define this with the first 2 sources, in the order we want it to be loaded and we leave a tag img that the browser will "inject" the first source that works.

  • Old browsers, all IE’s and various mobiles do not support <picture>

  • It is that in the question talks about Safari... I have not read anything about this restriction of old browser and I can not guess yet.

0

You can use picture tag:

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

Or

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

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 there is an interpretation error 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 out the path of your images:

 var dir = '/images/'
 if (navigator.userAgent.indexOf("Safari") != -1) { 
     dir = '/safari-images/';
 }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.