From c81a74a20ce10fe044d2959f965a873a06d69a2a Mon Sep 17 00:00:00 2001 From: Pavel Djundik Date: Wed, 6 Sep 2017 22:03:56 +0300 Subject: [PATCH] Render link previews in browser idle event Fixes #1504 --- client/js/socket-events/msg.js | 11 +++-------- client/js/socket-events/msg_preview.js | 6 +++--- client/js/utils.js | 13 ++++++++++++- 3 files changed, 18 insertions(+), 12 deletions(-) diff --git a/client/js/socket-events/msg.js b/client/js/socket-events/msg.js index 39b34bcf..4ef503ae 100644 --- a/client/js/socket-events/msg.js +++ b/client/js/socket-events/msg.js @@ -3,17 +3,12 @@ const $ = require("jquery"); const socket = require("../socket"); const render = require("../render"); +const utils = require("../utils"); const chat = $("#chat"); socket.on("msg", function(data) { - if (window.requestIdleCallback) { - // During an idle period the user agent will run idle callbacks in FIFO order - // until either the idle period ends or there are no more idle callbacks eligible to be run. - // We set a maximum timeout of 2 seconds so that messages don't take too long to appear. - window.requestIdleCallback(() => processReceivedMessage(data), {timeout: 2000}); - } else { - processReceivedMessage(data); - } + // We set a maximum timeout of 2 seconds so that messages don't take too long to appear. + utils.requestIdleCallback(() => processReceivedMessage(data), 2000); }); function processReceivedMessage(data) { diff --git a/client/js/socket-events/msg_preview.js b/client/js/socket-events/msg_preview.js index 42972d61..426bcf9b 100644 --- a/client/js/socket-events/msg_preview.js +++ b/client/js/socket-events/msg_preview.js @@ -3,9 +3,9 @@ const $ = require("jquery"); const renderPreview = require("../renderPreview"); const socket = require("../socket"); +const utils = require("../utils"); socket.on("msg:preview", function(data) { - const msg = $("#msg-" + data.id); - - renderPreview(data.preview, msg); + // Previews are not as important, we can wait longer for them to appear + utils.requestIdleCallback(() => renderPreview(data.preview, $("#msg-" + data.id)), 6000); }); diff --git a/client/js/utils.js b/client/js/utils.js index 00bb3416..46a8dccb 100644 --- a/client/js/utils.js +++ b/client/js/utils.js @@ -12,7 +12,8 @@ module.exports = { resetHeight, setNick, toggleNickEditor, - toggleNotificationMarkers + toggleNotificationMarkers, + requestIdleCallback, }; function resetHeight(element) { @@ -77,3 +78,13 @@ function move(array, old_index, new_index) { array.splice(new_index, 0, array.splice(old_index, 1)[0]); return array; } + +function requestIdleCallback(callback, timeout) { + if (window.requestIdleCallback) { + // During an idle period the user agent will run idle callbacks in FIFO order + // until either the idle period ends or there are no more idle callbacks eligible to be run. + window.requestIdleCallback(callback, {timeout: timeout}); + } else { + callback(); + } +}