我创建了一个功能,允许客户根据星期几在他的主页上拥有不同的背景。根据各种设备的屏幕宽度,我有四种不同尺寸的图像。我想找到一种方法来预览背景图像,以便页面加载更顺畅。这是预加载到底部的功能。这当前只加载最后一个大小“phone_background”,但我希望它为访问者的设备预加载相应的大小。感谢任何建议。
function my_custom_background(){
if ( ! is_front_page() ) {
return;
}
$img_id = get_field( strtolower( date( 'l' ) ) );
echo "<style>\n";
// Large desktops.
$size = 'large_desktop_background';
$img = wp_get_attachment_image_src( $img_id, 'large_desktop_background' );
echo "body {\n";
echo sprintf( "\tbackground-image: url(%s);\n", $img[0] );
echo "}\n";
// Small desktops.
$size = 'small_desktop_background';
$img = wp_get_attachment_image_src( $img_id, 'small_desktop_background' );
echo "@media (max-width: 1199px) {\n";
echo "\tbody {\n";
echo sprintf( "\t\tbackground-image: url(%s);\n", $img[0] );
echo "\t}\n";
echo "}\n";
// Tablets.
$size = 'tablet_background';
$img = wp_get_attachment_image_src( $img_id, 'tablet_background' );
echo "@media (max-width: 991px) {\n";
echo "\tbody {\n";
echo sprintf( "\t\tbackground-image: url(%s);\n", $img[0] );
echo "\t}\n";
echo "}\n";
// Mobile.
$size = 'phone_background';
$img = wp_get_attachment_image_src( $img_id, 'phone_background' );
echo "@media (max-width: 767px) {\n";
echo "\tbody {\n";
echo sprintf( "\t\tbackground-image: url(%s);\n", $img[0] );
echo "\t}\n";
echo "}\n";
echo "</style>\n";
$preload = "<div style='display:none;'>
<img src= '$img[0]' />
</div>";
echo $preload;
}
add_action( 'wp_head', 'my_custom_background' );