Browse Source
* Post.HTML() and PreviewHTML() both mogrify the resulting HTML code to ensure all <img> tags have loading="lazy" unless a loading attribute is already present.master
4 changed files with 90 additions and 10 deletions
@ -0,0 +1,35 @@ |
|||
package mogrify |
|||
|
|||
import ( |
|||
"fmt" |
|||
"regexp" |
|||
"strings" |
|||
) |
|||
|
|||
// Outgoing HTML filters for responses (experimental).
|
|||
|
|||
var reImgTag = regexp.MustCompile(`<img ([^>]+)>`) |
|||
|
|||
// LazyLoadImages modifies <img> tags to add loading="lazy" attribute to them.
|
|||
// Ignores image tags that already include the attribute.
|
|||
func LazyLoadImages(input string) string { |
|||
m := reImgTag.FindAllStringSubmatch(input, -1) |
|||
|
|||
if m == nil { |
|||
return input |
|||
} |
|||
|
|||
for _, match := range m { |
|||
var ( |
|||
tag = match[0] |
|||
attrs = match[1] |
|||
replace = fmt.Sprintf(`<img %s loading="lazy">`, attrs) |
|||
) |
|||
if strings.Contains(attrs, "loading=") { |
|||
continue |
|||
} |
|||
input = strings.Replace(input, tag, replace, -1) |
|||
} |
|||
|
|||
return input |
|||
} |
@ -0,0 +1,44 @@ |
|||
package mogrify_test |
|||
|
|||
import ( |
|||
"testing" |
|||
|
|||
"git.kirsle.net/apps/gophertype/pkg/mogrify" |
|||
) |
|||
|
|||
func TestLazyLoadImages(t *testing.T) { |
|||
var tests = []struct { |
|||
In string |
|||
Expect string |
|||
}{ |
|||
{ |
|||
In: `<img src="logo.jpg">`, |
|||
Expect: `<img src="logo.jpg" loading="lazy">`, |
|||
}, |
|||
{ |
|||
In: `<img src="https://example.com/image.png" loading="eager">`, |
|||
Expect: `<img src="https://example.com/image.png" loading="eager">`, |
|||
}, |
|||
{ |
|||
In: `Hello world`, |
|||
Expect: `Hello world`, |
|||
}, |
|||
{ |
|||
In: `<img src="a"><img src="b"><img src="a">`, |
|||
Expect: `<img src="a" loading="lazy"><img src="b" loading="lazy"><img src="a" loading="lazy">`, |
|||
}, |
|||
{ |
|||
In: `<img src="a"><img src="b" loading="eager"><img src="a">`, |
|||
Expect: `<img src="a" loading="lazy"><img src="b" loading="eager"><img src="a" loading="lazy">`, |
|||
}, |
|||
} |
|||
|
|||
for _, test := range tests { |
|||
actual := mogrify.LazyLoadImages(test.In) |
|||
if actual != test.Expect { |
|||
t.Errorf("for input {%s} I expected {%s} but got: {%s}", |
|||
test.In, test.Expect, actual, |
|||
) |
|||
} |
|||
} |
|||
} |
Loading…
Reference in new issue