From 703349de9d7b4b4ef6b4b39b396c34f21c9153fb Mon Sep 17 00:00:00 2001 From: Cell <1024@lruihao.cn> Date: Sat, 11 Feb 2023 23:14:49 +0800 Subject: [PATCH] :zap: Perf: optimze image lazy loading --- assets/css/_page/_single.scss | 5 ++++- layouts/partials/plugin/image.html | 11 +++++++---- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/assets/css/_page/_single.scss b/assets/css/_page/_single.scss index 3676cbd5..90ff2bd8 100644 --- a/assets/css/_page/_single.scss +++ b/assets/css/_page/_single.scss @@ -271,6 +271,10 @@ img { max-width: 100%; min-height: 1em; + + &:not([data-h]) { + height: auto; + } } svg { max-width: 100%; @@ -292,7 +296,6 @@ img { display: block; - height: auto; margin: 0 auto; overflow: hidden; diff --git a/layouts/partials/plugin/image.html b/layouts/partials/plugin/image.html index 803f47eb..96fcd4c7 100644 --- a/layouts/partials/plugin/image.html +++ b/layouts/partials/plugin/image.html @@ -5,7 +5,7 @@ {{- with dict "Path" $src "Resources" .Resources | partial "function/resource.html" -}} {{- $src = .RelPermalink -}} {{- /* Resources can not get width and height of image for svg type */ -}} - {{- if (not $width) | and (not $height) | and (ne .MediaType.SubType "svg") -}} + {{- if (not $.Width) | and (not $.Height) | and (ne .MediaType.SubType "svg") -}} {{- $width = .Width -}} {{- $height = .Height -}} {{- end -}} @@ -24,8 +24,8 @@ {{- $alt := .Alt | default $src -}} {{- $caption := .Caption | default $alt -}} {{- $loading := .Loading | default "lazy" -}} -{{- $commonScript := "this.removeAttribute('style');this.removeAttribute('onerror');this.removeAttribute('onload');" -}} -{{- $onload := printf " onload=\"this.dataset.lazyloaded='';%v\"" $commonScript | safeHTMLAttr -}} +{{- $commonScript := "this.title=this.dataset.title;this.alt=this.dataset.alt;for(const a of ['style','data-title','data-alt','onerror','onload']){this.removeAttribute(a);}" -}} +{{- $onload := printf " onload=\"%vthis.dataset.lazyloaded='';\"" $commonScript | safeHTMLAttr -}} {{- $onerror := printf " onerror=\"%v\"" $commonScript | safeHTMLAttr -}} {{- $style := printf " style=\"background: url(%v) no-repeat center;\"" (resources.Get "svg/loading.svg" | minify).RelPermalink | safeHTMLAttr -}} {{- if eq $loading "eager" -}} @@ -37,13 +37,16 @@ {{- if .Linked -}} {{- end -}} -{{ $alt }} {{- if .Linked -}}