简体   繁体   中英

Auto-populate the image url

I'm checking if the browser is chrome or not. If that is chrome, then I am showing only Webp image with the attribute (data-mobileWebp) or (data-desktopWebp). Sometimes, webp images won't be uploaded in backend then I need to fall back to the normal image which is uploaded always like data-mobileImage or data-desktopImage

Here the code which is not working as expected is :

mobileImage = $('.mobileImages', picture).data('mobileWebp') != null ? $('.mobileImages', picture).attr('data-mobileWebp') : $('.mobileImages', picture).attr('data-mobileImage');
desktopImage = $('.desktop-images', picture).data('desktopWebp') != null ? $('.desktop-images', picture).attr('data-desktopWebp') : $('.desktop-images', picture).attr('data-desktopImage');

 var is_chrome = (typeof window.chrome === 'object' && navigator.appVersion.indexOf('Edge') === -1); var imageBrowsers = $('.image-browsers'); if (imageBrowsers.length > 0) { imageBrowsers.each(function(picture) { var mobileImage, desktopImage; if (is_chrome) { mobileImage = $('.mobileImages', picture).data('mobileWebp') != null ? $('.mobileImages', picture).attr('data-mobileWebp') : $('.mobileImages', picture).attr('data-mobileImage'); desktopImage = $('.desktop-images', picture).data('desktopWebp') != null ? $('.desktop-images', picture).attr('data-desktopWebp') : $('.desktop-images', picture).attr('data-desktopImage'); } else { mobileImage = $('.mobileImages', picture).attr('data-mobileImage'); desktopImage = $('.desktop-images', picture).attr('data-desktopImage') } $('.mobileImages', picture).attr('srcset', mobileImage); $('.desktop-images', picture).attr('src', desktopImage); }); } 
 <isif condition="${desktopImage || mobileImage}"> <picture class="image-browsers"> <isif condition="${mobileImage}"> <source class="mobileImages" srcset="" media="(max-width: 768px)" data-mobileImage="${mobileImage ? mobileImage.getURL() : ''}" data-mobileWebp="${mobilewebpImage ? mobilewebpImage.getURL() : ''}"> </isif> <isif condition="${desktopImage}"> <img class="desktop-images" src="" alt="${'previewName' in contentAsset.custom && contentAsset.custom.previewName != null ? contentAsset.custom.previewName : '' }" title="${'previewName' in contentAsset.custom && contentAsset.custom.previewName != null ? contentAsset.custom.previewName : '' }" data-desktopImage="${desktopImage ? desktopImage.getURL() : ''}" data-desktopWebp="${desktopwebpImage ? desktopwebpImage.getURL() : ''}"> </isif> </picture> </isif> 

Why don't you use Modernizr?

Modernizr.on('webp', function (result) {

  console.log(result);  
  if (result) {
    // Has WebP support
  }
  else {
    // No WebP support
  }
});

http://www.stucox.com/blog/using-webp-with-modernizr/

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