SEO 首图预加载

This commit is contained in:
tangly1024.com
2023-07-21 12:29:52 +08:00
parent 4d5e684f19
commit 8da4af6a03
2 changed files with 33 additions and 12 deletions

View File

@@ -4,15 +4,15 @@ import React, { useEffect, useRef, useState } from 'react'
* 默认懒加载占位图
*/
const loadingSVG = (
<svg
width="100"
height="100"
viewBox="0 0 100 100"
xmlns="http://www.w3.org/2000/svg"
fill="#ccc"
>
<circle cx="50" cy="50" r="42" strokeWidth="8" />
</svg>
<svg
width="100"
height="100"
viewBox="0 0 100 100"
xmlns="http://www.w3.org/2000/svg"
fill="#ccc"
>
<circle cx="50" cy="50" r="42" strokeWidth="8" />
</svg>
)
/**
@@ -20,7 +20,18 @@ const loadingSVG = (
* @param {*} param0
* @returns
*/
export default function LazyImage({ id, src, alt, placeholderSrc = loadingSVG, className, width, height, onLoad, style }) {
export default function LazyImage({
priority,
id,
src,
alt,
placeholderSrc = loadingSVG,
className,
width,
height,
onLoad,
style
}) {
const imageRef = useRef(null)
const [imageLoaded, setImageLoaded] = useState(false)
@@ -31,6 +42,17 @@ export default function LazyImage({ id, src, alt, placeholderSrc = loadingSVG, c
}
}
// 预加载图片
useEffect(() => {
if (priority) {
const link = document.createElement('link')
link.rel = 'preload'
link.as = 'image'
link.href = src
document.head.appendChild(link)
}
}, [priority, src])
useEffect(() => {
const observer = new IntersectionObserver(
(entries) => {

View File

@@ -3,7 +3,6 @@ import CONFIG from '../config'
import BLOG from '@/blog.config'
import TagItemMini from './TagItemMini'
import LazyImage from '@/components/LazyImage'
// import Image from 'next/image'
const BlogPostCard = ({ index, post, showSummary, siteInfo }) => {
const showPreview = CONFIG.POST_LIST_PREVIEW && post.blockMap
@@ -20,7 +19,7 @@ const BlogPostCard = ({ index, post, showSummary, siteInfo }) => {
{showPageCover && (
<div className="w-full md:w-5/12 2xl:w-full overflow-hidden">
<Link href={`${BLOG.SUB_PATH}/${post.slug}`} passHref legacyBehavior>
<LazyImage src={post?.pageCoverThumbnail} alt={post?.title} className='h-60 w-full object-cover group-hover:scale-105 group-hover:brightness-75 transition-all duration-300'/>
<LazyImage priority={index === 0} src={post?.pageCoverThumbnail} alt={post?.title} className='h-60 w-full object-cover group-hover:scale-105 group-hover:brightness-75 transition-all duration-300'/>
</Link>
</div>
)}