From b8f7e622bbee068ac9e6a96c2307dbc7d7b02b14 Mon Sep 17 00:00:00 2001 From: Laria Carolin Chabowski Date: Wed, 14 Oct 2020 22:52:21 +0200 Subject: Lazy load background image using XHR We now don't immediately reload the reddit background image, as this delays the initial page load quite a bit. Instead we trigger an XHR request on page load to update the background image. --- reddit_background/reddit_background.go | 38 +++++++++++++++++++++++++++------- 1 file changed, 31 insertions(+), 7 deletions(-) (limited to 'reddit_background') diff --git a/reddit_background/reddit_background.go b/reddit_background/reddit_background.go index 67b25d0..60ba4ec 100644 --- a/reddit_background/reddit_background.go +++ b/reddit_background/reddit_background.go @@ -41,6 +41,23 @@ type RedditImage struct { Mediatype string `json:"-"` } +type RedditImageForAjax struct { + Permalink string + Title string + Saved bool +} + +func (ri *RedditImage) ForAjax() *RedditImageForAjax { + if ri == nil { + return nil + } + return &RedditImageForAjax{ + Permalink: ri.Permalink, + Title: ri.Title, + Saved: ri.Saved, + } +} + func GetRedditImage(maxsize int, subreddit string) (*RedditImage, error) { subredditUrl := fmt.Sprintf("https://www.reddit.com/r/%s.json", subreddit) @@ -211,21 +228,28 @@ func NewRedditImageProvider(maxsize int, subreddit string) *RedditImageProvider } } -func (rip *RedditImageProvider) Image() *RedditImage { +func (rip *RedditImageProvider) UpdateImage() bool { + updated := false + rip.intervalRunner.Run(func() bool { log.Printf("Getting new RedditImage") - var err error - rip.image, err = GetRedditImage(rip.maxsize, rip.subreddit) + image, err := GetRedditImage(rip.maxsize, rip.subreddit) - if err == nil { - log.Printf("Successfully loaded RedditImage") - } else { + if err != nil { log.Printf("Failed loading RedditImage: %s", err) + return false } - return err == nil + log.Printf("Successfully loaded RedditImage") + rip.image = image + updated = true + return true }) + return updated +} + +func (rip *RedditImageProvider) Image() *RedditImage { return rip.image } -- cgit v1.2.3-70-g09d2