首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Wordpress和懒散的负载,我不能让它工作

问Wordpress和懒散的负载,我不能让它工作
EN

Stack Overflow用户
提问于 2013-05-20 23:55:51
回答 4查看 1.2K关注 0票数 0

我试图让懒惰加载js工作在一个wordpress网站,不能为我的生活使它工作。我尝试了插件,当他们工作时,他们懒得加载所有的图片,我不能让这种情况出现在我的主页上(说来话长,但这会引起跳跃式问题)。我只想在特定的页面上延迟加载图像。在过去,我只需链接到js文件,并将这个类延迟添加到我想要的图像中,但这显然是行不通的。我累了..。

functions.php

代码语言:javascript
复制
function load_lazyload() {
    wp_register_script( 'lazyload', get_template_directory_uri() . '/library/js/jquery.lazyload.min.js', array(), '', true );
    wp_register_script( 'trigger_lazy', get_template_directory_uri() . '/library/js/lazy_trigger.js', array('jquery', 'lazyload'), '', true );
    wp_enqueue_script( 'trigger_lazy' );
}
add_action( 'wp_enqueue_scripts', 'load_lazyload' );

然后将其添加到lazy_trigger.js中

代码语言:javascript
复制
jQuery(document).ready(function($) {
$("img.lazy").lazyload({
    effect : "fadeIn"
});

});

然后,我将这个类延迟添加到我想要加载的图像中。

没办法让这件事成功。有人能解释为什么,或者更好地解释一个更好的方法吗?

EN

回答 4

Stack Overflow用户

发布于 2013-05-21 00:34:37

假设您使用的是这个jQuery插件,则必须(a)为src属性指定默认图像,(b)将实际映像的url添加为html5数据属性,例如:

代码语言:javascript
复制
foreach( $posts as $post ) {
    setup_postdata( $post ); 
    $src = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'thumbnail', false, '' );
    $img = '<img class="lazy" src="' . get_template_directory_uri() . '/images/default.png" data-original="' . $src[0] . '" />';
    echo $img;
}
票数 0
EN

Stack Overflow用户

发布于 2013-07-01 22:06:51

实际上,有一个wordpress延迟加载插件可以轻松安装--只需在插件部分搜索惰性加载即可。

票数 0
EN

Stack Overflow用户

发布于 2020-10-30 15:53:43

其实施方式如下:

代码语言:javascript
复制
add_filter( 'save_post', 'add_lazy_load', 10, 3 ); 
function add_lazy_load($post_id, $post, $update) 
{ 
if (wp_is_post_revision($post_id))
 { 
return; 
} 
if ( ! class_exists( 'DOMDocument', false ) ) 
return; 
remove_action('save_post', 'add_lazy_load'); 
$post_status = get_post_status(); 
if ($post_status != 'draft') 
{ 
$document = new DOMDocument();
$document->loadHTML(mb_convert_encoding($post->post_content, 'HTML-ENTITIES', 'UTF-8')); $images = $document-getElementsByTagName('img'); 
foreach ($images as $image) 
{ 
$image->getAttribute('load'); 
if (!$image->getAttribute('loading') || $image->getAttribute('loading') != 'lazy') 
{ 
$image->setAttribute('loading', 'lazy');
 } 
}
$iframes = $document->getElementsByTagName('iframe'); 
foreach ($iframes as $iframe) 
{ 
$iframe->getAttribute('load'); 
if (!$iframe->getAttribute('loading') || $iframe->getAttribute('loading') != 'lazy') 
{ 
$iframe->setAttribute('loading', 'lazy'); 
} 
} 
$html = $document-saveHTML(); 
wp_update_post(array( "ID" = $post_id, "post_content" => html_entity_decode($html), )); 
} 
add_action('save_post', 'add_lazy_load', 10, 3); 
}

阅读更多:https://www.plerdy.com/blog/lazy-loading-setup-wordpress/

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16660068

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档