在WordPress中使用AJAX导航时,预加载图片可以通过使用JavaScript(或jQuery)和Ajax请求来实现
functions.php
文件中,以便在单击页面链接时触发Ajax请求:function ajax_content_init() {
wp_enqueue_script('ajax-content', get_template_directory_uri() . '/ajax-content.js', array('jquery'), '1.0', true);
// 添加Ajax调用支持
add_action('wp_ajax_get_content', 'get_content');
add_action('wp_ajax_nopriv_get_content', 'get_content'); // 对于未登录用户
}
function get_content() {
$post_id = isset($_POST['post_id']) ? intval($_POST['post_id']) : 0;
$post = get_post($post_id);
if ($post) {
setup_postdata($post);
get_template_part('content', get_post_format($post));
wp_reset_postdata();
} else {
_e("加载失败,请稍后重试。", "text-domain");
}
wp_die();
}
add_action('init', 'ajax_content_init');
ajax-content.js
的文件,其中包含AJAX请求的JavaScript代码:jQuery(document).ready(function($) {
$('body').on('click', '.ajax-link', function(e) {
e.preventDefault();
var post_id = $(this).data('post-id');
$.ajax({
type: 'POST',
url: ajaxurl, // WordPress AJAX 功能的URL
type: 'POST',
data: {
action: 'get_content',
post_id: post_id,
},
success: function(response) {
// 将返回的内容插入到页面中,并更新导航
$('#content').html(response);
// 预加载图片
preloadImages();
},
error: function() {
alert('加载失败,请稍后重试。');
}
});
});
function preloadImages() {
// 获取需要预加载的所有图片
var images = $('.ajax-link').map(function() {
return $(this).attr('src');
}).get();
// 预加载图片
images.forEach(function(imageUrl) {
var img = new Image();
img.src = imageUrl;
});
}
});
这个脚本会在单击 .ajax-link
类的链接时触发AJAX请求。接着,它将返回的内容插入到页面中的 #content
元素,并调用 preloadImages()
函数来预加载页面上的图片。
preloadImages()
函数首先获取页面上所有需要预加载的图片的URL。然后,它遍历这些URL,并创建一个新的 Image
对象。通过设置新对象的 src
属性,浏览器将开始加载图片,从而实现预加载。
现在,当使用AJAX导航时,页面上的图片将被预加载,从而提高用户体验。
没有搜到相关的文章