added lazy loading to img for blogs

This commit is contained in:
partisan 2024-08-29 22:48:04 +02:00
parent 0f3895bebd
commit 37a628ad09

42
main.go
View file

@ -216,6 +216,41 @@ func renderIndex(w http.ResponseWriter) {
renderTemplate(w, "index.html", nil)
}
// Helper function to add loading="lazy" to all img tags
func injectLazyLoading(htmlContent string) string {
// Split the content by <img tags to process them individually
parts := strings.Split(htmlContent, "<img")
// Start with the first part which is before any <img tag
modifiedContent := parts[0]
// Iterate over the remaining parts
for _, part := range parts[1:] {
// Find the closing bracket of the img tag
endOfTag := strings.Index(part, ">")
if endOfTag == -1 {
// If no closing bracket is found, add the remaining part as is
modifiedContent += "<img" + part
continue
}
// Extract the actual <img tag
imgTag := part[:endOfTag]
// Check if loading="lazy" is already present
if !strings.Contains(imgTag, "loading=") {
// Insert loading="lazy" before the closing of the img tag
imgTag = " loading=\"lazy\"" + imgTag
}
// Rebuild the full content with the modified img tag
modifiedContent += "<img" + imgTag + part[endOfTag:]
}
return modifiedContent
}
// For redering HTML Blogs
func renderBlogEntry(w http.ResponseWriter, r *http.Request, blogName string, entryNumber int) {
var blog Blog
for _, b := range blogs {
@ -249,16 +284,21 @@ func renderBlogEntry(w http.ResponseWriter, r *http.Request, blogName string, en
}
}
// Convert .md to HTML
htmlContent := blackfriday.Run([]byte(entry.Content))
// Double check "/news-assets/" in URL of images
htmlContent = bytes.ReplaceAll(htmlContent, []byte("src=\"./"), []byte(fmt.Sprintf("src=\"/news-assets/%d/", entryNumber)))
// Apply lazy loading to the generated HTML content
htmlContentWithLazyLoading := injectLazyLoading(string(htmlContent))
pageData := PageData{
Title: entry.Title,
Date: entry.Date.Format("2006-01-02 15:04"),
Desc: entry.Description,
Author: entry.Author,
Content: template.HTML(htmlContent),
Content: template.HTML(htmlContentWithLazyLoading),
PrevLink: prevLink,
NextLink: nextLink,
}