SVG / PNG switch

Is there a way to use SVG images on my site, and if browsers / devices do not support it, switch the extension to png? Is there a better way to do this?

Note. I use the <img> and Modernizr.

Here is my code that splashes images dynamically.

 <?php $attachments = attachments_get_attachments(); ?> <?php if( function_exists( 'attachments_get_attachments' ) ) { $attachments = attachments_get_attachments(); $total_attachments = count( $attachments ); if( $total_attachments ) : ?><?php for( $i=0; $i<$total_attachments; $i++ ) : ?> <img src="<?php echo $attachments[$i]['location']; ?>" alt="<?php echo $attachments[$i]['title']; ?>" class="full" /> <?php endfor; ?><?php endif; ?><?php } ?> 

Outputs the following: <img src="http://mysiteurl.net/image.png" alt="Image Title" class="full wp-image-287" />

+4
source share
3 answers

I assume that you can check if svg supported, and if you do not scroll the image tags and set their src path to .png . This example has not been tested, but it could be a step in the right direction.

 if(!Modernizr.svg){ var images = document.getElementsByTagName("img"); for(var i = 0; i < images.length; i++){ var src = images[i].src.split("."); images[i].src = src[0] + ".png"; } } 

If jQuery is an option, maybe something like this:

 if(!Modernizr.svg){ $("img").each(function(){ var src = this.src.split("."); this.src = src[0] + ".png"; }); } 

EDIT

You may also consider looking for Modernizr-Server . This way you can test svg while you view the images and add the appropriate extension.

 if ($modernizr->svg) { ... } elseif ($modernizr->canvas) { ... } 
+1
source

This works by filtering only the svg file

 <script type="text/javascript"> jQuery( document ).ready(function() { if(!Modernizr.svg){ jQuery("img").each(function(){ var src = this.src; if( src.match(/svg$/) ){ // Replace "svg" by "png" this.src = src.slice(0,-3) + 'png' } }); } }); </script> 
+3
source

An alternative is to use a CSS-ony solution for SVG with redundancy as described in this answer: fooobar.com/questions/17780 / ...

+1
source

Source: https://habr.com/ru/post/1439240/


All Articles