Skip to content

Commit 1b4a45e

Browse files
authored
feat: Let the browser decide which image quality to load (#172)
Use `srcset` instead of individual sources: https://developer.mozilla.org/en-US/docs/Web/HTML/Guides/Responsive_images
1 parent ee62d51 commit 1b4a45e

File tree

1 file changed

+23
-29
lines changed

1 file changed

+23
-29
lines changed

layouts/partials/image.html

Lines changed: 23 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
{{ $loading := "lazy" }}
33

44
{{ if .Permalink }}
5-
{{ $image = . }}
5+
{{ $image = . }}
66
{{ else if .image }}
77
{{ $image = .image }}
88
{{ if .eager }}
@@ -11,35 +11,29 @@
1111
{{ end }}
1212

1313
<picture>
14-
{{ $widths := slice }}
15-
16-
{{ if gt $image.Width 2200 }}
17-
{{ $widths = $widths | append 2200 }}
18-
{{ end }}
19-
{{ if gt $image.Width 1500 }}
20-
{{ $widths = $widths | append 1500 }}
21-
{{ end }}
22-
{{ if gt $image.Width 1200 }}
23-
{{ $widths = $widths | append 1200 }}
24-
{{ end }}
25-
{{ if gt $image.Width 800 }}
26-
{{ $widths = $widths | append 800 }}
27-
{{ end }}
28-
{{ if gt $image.Width 500 }}
29-
{{ $widths = $widths | append 500 }}
30-
{{ end }}
14+
{{- $widths := slice -}}
15+
{{- if gt $image.Width 2200 -}}
16+
{{- $widths = $widths | append 2200 -}}
17+
{{- end -}}
18+
{{- if gt $image.Width 1500 -}}
19+
{{- $widths = $widths | append 1500 -}}
20+
{{- end -}}
21+
{{- if gt $image.Width 1200 -}}
22+
{{- $widths = $widths | append 1200 -}}
23+
{{- end -}}
24+
{{- if gt $image.Width 800 -}}
25+
{{- $widths = $widths | append 800 -}}
26+
{{- end -}}
27+
{{- if gt $image.Width 500 -}}
28+
{{- $widths = $widths | append 500 -}}
29+
{{- end -}}
3130

32-
{{- range $i, $width := $widths }}
31+
{{- $srcset := slice -}}
32+
{{- range $i, $width := $widths -}}
3333
{{- with $image.Resize (printf "%dx" $width) -}}
34-
<!-- Important: Do not change the indentation, otherwise the image is rendered as pre in some cases -->
35-
<source media="(min-width:{{ $width }}px)" srcset="{{ .RelPermalink | safeURL }}" title="{{ $.Title }}" loading="{{ $loading }}"/>
36-
{{- end }}
37-
{{- end }}
38-
39-
{{- $tinyImage := $image -}}
40-
{{- if gt $image.Width 500 -}}
41-
{{- $tinyImage = $image.Resize "500x" -}}
34+
{{- $srcset = $srcset | append (printf "%s %dw" .RelPermalink $width) -}}
35+
{{- end -}}
4236
{{- end -}}
43-
<!-- Important: Do not change the indentation, otherwise the image is rendered as pre in some cases -->
44-
<img src="{{ $tinyImage.RelPermalink | safeURL }}" alt="{{ $.Title }}" title="{{ $.Title }}" loading="{{ $loading }}"/>
37+
38+
{{- printf "<img src=\"%s\" alt=\"%s\" title=\"%s\" loading=\"%s\" srcset=\"%s\"/>" $image.RelPermalink $.Title $.Title $loading (delimit $srcset ", ") | safeHTML -}}
4539
</picture>

0 commit comments

Comments
 (0)