36 lines
700 B
Go
36 lines
700 B
Go
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
|
|
}
|