The editor is sometimes nearly unusable when there's a snippet or two in the post, so I wrote a userscript to intercept and block the events that trigger the post re-rendering.
Example screenshots are from this post, which has 3 snippets.
Before:
Every keystroke attempts to update the live preview, and that operation is very expensive. Neither the textarea nor the preview respond anywhere near quickly enough, which is a problem for those of us who aren't perfect typers.
After:
The script intercepts the key events in the capturing phase and uses stopPropagation()
to ensure it doesn't reach the textarea, which would result in a re-rendering. Instead, after a key event, a re-render function is put into a setTimeout
which is cleared after each keystroke - so, it'll only run once the last keystroke was more than ~700ms ago. Moving the mouse will also trigger the re-render immediately.
The code:
// ==UserScript==
// @name Stack Snippet Lag Fixer
// @description Prevents post previews with stack snippets from continuously re-rendering
// @author CertainPerformance
// @include https://stackoverflow.com/questions/*
// @version 1.0
// @grant none
// ==/UserScript==
// Milliseconds to wait after typing before a re-render:
const msDelay = 700;
const queueRender = (() => {
// To avoid re-creating render functions every time an event is triggered,
// use a persistent Map of elements to their render functions:
const renderFnsMap = new Map();
let timeout;
const getRenderFn = (elm) => {
if (renderFnsMap.has(elm)) {
return renderFnsMap.get(elm);
}
const render = () => {
elm.dispatchEvent(new Event('input'));
clearTimeout(timeout);
document.removeEventListener('mousemove', render);
};
renderFnsMap.set(elm, render);
return render;
};
// queueRender function: Call render after msDelay or after a mousemove event,
// whichever comes first:
return (elm) => {
const render = getRenderFn(elm);
clearTimeout(timeout);
timeout = setTimeout(render, msDelay);
document.addEventListener('mousemove', render);
};
})();
const hasSnippet = textarea => textarea.value.includes('<!-- begin snippet');
const handler = (event) => {
// .wmd-input: question and answer textboxes, for both posting and editing
// isTrusted check required so that the dispatched event above isn't caught
const { target, isTrusted } = event;
if (target.matches('.wmd-input') && isTrusted && hasSnippet(target)) {
event.stopPropagation();
queueRender(target);
}
};
// All of these events trigger the re-render by default:
const eventNames = ['keypress', 'keydown', 'input'];
eventNames.forEach((eventName) => {
// Must intercept the event in the capturing phase, before the event reaches the textarea:
document.addEventListener(eventName, handler, true);
});