在视口上的大型菜单中延迟加载图像

时间:2021-03-06 22:23:42

标签: woocommerce

我有以下自定义代码,用于在视口的超级菜单中包含延迟加载图像。但是,它们有时会出错并且图像无法加载。观看视频 https://sgevcen.tinytake.com/tt/NTE3MjUwM18xNjE5ODIzNA

有人可以帮我理解代码中出了什么问题吗?谢谢

 * LAZYLOAD IMAGES FROM MEGA MENUS ON DESKTOP (COMPELMENTARY TO CUSTOM JS CODE)
 */
add_action(
    'woodmart_after_body_open',
    function() {
        remove_action( 'woodmart_attachment', 'woodmart_lazy_attachment_replace', 10) ;
        add_filter('woodmart_attachment', 'woodmart_custom_lazy_attachment_replace', 10, 3);
    }
);
add_action(
    'woodmart_after_header',
    function() {
        add_filter('woodmart_attachment', 'woodmart_lazy_attachment_replace', 10, 3);
        remove_action( 'woodmart_attachment', 'woodmart_custom_lazy_attachment_replace', 10) ;
    }
);
function woodmart_custom_lazy_attachment_replace( $imgHTML, $attach_id, $size ) {
    if ( preg_match( "/src=['\"]data:image/is", $imgHTML ) ) return $imgHTML;
    if( $attach_id ) {
        $lazy_image = woodmart_get_attachment_placeholder( $attach_id, $size );
    } else {
        $lazy_image = woodmart_lazy_get_default_preview();
    }
    return  woodmart_custom_lazy_replace_image( $imgHTML, $lazy_image );
}
function woodmart_custom_lazy_replace_image( $html, $src ) {
    $class = woodmart_custom_lazy_css_class();
    $new = preg_replace( '/<img(.*?)src=/is', '<img$1src="'.$src.'" data-wood-src=', $html );
    $new = preg_replace( '/<img(.*?)srcset=/is', '<img$1srcset="" data-srcset=', $new );
    if ( preg_match( '/class=["\']/i', $new ) ) {
        $new = preg_replace( '/class=(["\'])(.*?)["\']/is', 'class=$1' . $class . ' $2$1', $new );
    } else {
        $new = preg_replace( '/<img/is', '<img class="' . $class . '"', $new );
    }
    return $new;
}
function woodmart_custom_lazy_css_class() {
    $class = 'woodmart-lazy-load-custom';
    $class .= ' woodmart-lazy-' . woodmart_get_opt( 'lazy_effect' );
    return $class;
}


/**
 * Lazyload images from mega menus on desktop (complementary to custom php code)
 */
jQuery('.whb-navigation li').hover(function() {
   customLazy(jQuery(this));
});
jQuery('.whb-navigation li').on('mousemove',function() {
   customLazy(jQuery(this));
});
function customLazy($this){
    $this.find('.woodmart-lazy-load-custom').each(function() {
        var $img = jQuery(this);
        $img.attr('src', jQuery(this).data('wood-src'));
        $img.addClass('woodmart-loaded');
        var $categories = $img.parents('.categories-masonry');
        if ($categories.length > 0) {
            $categories.imagesLoaded(function() {
                $categories.packery();
            });
        }
    });
}```

0 个答案:

没有答案
相关问题