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.
 
 

36 rivejä
700 B

  1. package mogrify
  2. import (
  3. "fmt"
  4. "regexp"
  5. "strings"
  6. )
  7. // Outgoing HTML filters for responses (experimental).
  8. var reImgTag = regexp.MustCompile(`<img ([^>]+)>`)
  9. // LazyLoadImages modifies <img> tags to add loading="lazy" attribute to them.
  10. // Ignores image tags that already include the attribute.
  11. func LazyLoadImages(input string) string {
  12. m := reImgTag.FindAllStringSubmatch(input, -1)
  13. if m == nil {
  14. return input
  15. }
  16. for _, match := range m {
  17. var (
  18. tag = match[0]
  19. attrs = match[1]
  20. replace = fmt.Sprintf(`<img %s loading="lazy">`, attrs)
  21. )
  22. if strings.Contains(attrs, "loading=") {
  23. continue
  24. }
  25. input = strings.Replace(input, tag, replace, -1)
  26. }
  27. return input
  28. }