From 0d5b6dd7e337fa78c628c7d962d2dd02cbca59b7 Mon Sep 17 00:00:00 2001 From: moris Date: Thu, 3 Apr 2025 19:08:31 +0900 Subject: [PATCH] =?UTF-8?q?img=E3=81=ABloading=3Dlazy=E3=82=92=E8=BF=BD?= =?UTF-8?q?=E5=8A=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/lib/components/Markdown/Markdown.ts | 2 ++ src/lib/components/Markdown/rehypeLazyImg.ts | 17 +++++++++++++++++ 2 files changed, 19 insertions(+) create mode 100644 src/lib/components/Markdown/rehypeLazyImg.ts diff --git a/src/lib/components/Markdown/Markdown.ts b/src/lib/components/Markdown/Markdown.ts index 62a7dc2..fad97e6 100644 --- a/src/lib/components/Markdown/Markdown.ts +++ b/src/lib/components/Markdown/Markdown.ts @@ -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) diff --git a/src/lib/components/Markdown/rehypeLazyImg.ts b/src/lib/components/Markdown/rehypeLazyImg.ts new file mode 100644 index 0000000..4a08874 --- /dev/null +++ b/src/lib/components/Markdown/rehypeLazyImg.ts @@ -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) + } +} \ No newline at end of file