imgにloading=lazyを追加

This commit is contained in:
moris 2025-04-03 19:08:31 +09:00
parent 98bd10f565
commit 0d5b6dd7e3
2 changed files with 19 additions and 0 deletions

View file

@ -12,6 +12,7 @@ import rehypeExternalLinks from 'rehype-external-links'
import rehypeGithubAlert from 'rehype-github-alert'
import rehypeStringify from 'rehype-stringify'
import rehypeHeaderLinks from 'rehype-header-links'
import rehypeLazyImg from './rehypeLazyImg'
function Perser(mdtext: string): string {
@ -22,6 +23,7 @@ function Perser(mdtext: string): string {
.use(remarkRehype, {allowDangerousHtml: true})
.use(rehypeSlug) // headingにidを設定
.use(rehypeKatex, {output:'mathml'}) // 数式
.use(rehypeLazyImg)
.use(rehypeHighlight) // Syntax highlight
.use(rehypeExternalLinks, {target:'_blank', rel:['noreferrer','noopener']}) // 外部サイトを新規タブで開く
.use(rehypeGithubAlert)

View file

@ -0,0 +1,17 @@
import type { Root, RootContent } from 'hast'
export default function rehypeLazyImg() {
return function(tree: Root) {
function loop(children: RootContent[]){
for (let child of children) {
if (child.type == 'element' && child.tagName == 'img') {
child.properties.loading = 'lazy'
}
if ('children' in child) {
loop(child.children)
}
}
}
return loop(tree.children)
}
}