Skip to content

Commit

Permalink
Save server requests by caching hasAvatar globally
Browse files Browse the repository at this point in the history
Improve performance by saving repeated HTTP calls when retrieving
information whether a user has an avatar set. Note that even HTTP calls
that hit the cache cause a delay.

This is useful to avoid flickering when switching/re-rendering vue
components that render avatars.

Signed-off-by: Vincent Petry <[email protected]>
  • Loading branch information
PVince81 committed Oct 15, 2020
1 parent 130c95d commit 090b666
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions src/components/Avatar/Avatar.vue
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,14 @@ import Tooltip from '../../directives/Tooltip'
import usernameToColor from '../../functions/usernameToColor'
import { userStatus } from '../../mixins'

function getUserHasAvatar(userId) {
return window.sessionStorage.getItem('userHasAvatar-' + userId)
}

function setUserHasAvatar(userId, flag) {
window.sessionStorage.setItem('userHasAvatar-' + userId, flag)
}

export default {
name: 'Avatar',
directives: {
Expand Down Expand Up @@ -466,17 +474,34 @@ export default {
urlGenerator(this.user, this.size * 4) + ' 4x',
].join(', ')

// skip loading
const userHasAvatar = getUserHasAvatar(this.user)
if (userHasAvatar !== undefined) {
this.isAvatarLoaded = true
this.avatarUrlLoaded = avatarUrl
if (!this.isUrlDefined) {
this.avatarSrcSetLoaded = srcset
}
if (userHasAvatar === false) {
this.userDoesNotExist = true
}
return
}

const img = new Image()
img.onload = () => {
this.avatarUrlLoaded = avatarUrl
if (!this.isUrlDefined) {
this.avatarSrcSetLoaded = srcset
}
this.isAvatarLoaded = true
// re-get to avoid concurrent access
setUserHasAvatar(this.user, true)
}
img.onerror = () => {
this.userDoesNotExist = true
this.isAvatarLoaded = true
setUserHasAvatar(this.user, false)
}

if (!this.isUrlDefined) {
Expand Down

0 comments on commit 090b666

Please sign in to comment.