A web blog and personal homepage engine written in Go.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

35 lines
700 B

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
}