11

When writing detailed answers, I need to use many stack snippets to show different states in order to explain some complex behavior, but this makes the editor terribly slow and annoying. I see my self obliged to use Notepad or something else to write the answer then do a copy/paste.

By many stack snippet I mean around 5/6 (I reached 9 for a recent answer, and it was a pain to edit...). The quantity of code inside has probably an impact also.

Why such behavior? What is the technical stuff behind that? Did anyone face a similar issue?

In my opinion, it's the preview that is constantly refreshing and it needs a lot of resources when there is many stack snippets. Is this true?

Besides the reason, is there a way to fix this?

6
  • 1
    I encounter this too. Your example post is really sluggish for me, I wonder if there's a way to fix it with a userscript Commented Dec 8, 2018 at 0:32
  • @CertainPerformance yes very annoying and the above example is nothing compared to this one : stackoverflow.com/questions/51731106/… where I really suffered ... Commented Dec 8, 2018 at 0:35
  • 1
    @CertainPerformance It's sluggish because the preview update is called upon every keypress and a single update of the preview takes a user-noticeable amount of time. This happens because the people who wrote the page made the assumption that the preview update would take a negligible amount of time. It is possible to improve the response by causing the updates to happen only when there's a break in user input, which is a common method of dealing with this type of issue.
    – Makyen Mod
    Commented Dec 8, 2018 at 23:36
  • 1
    Note: The preview update code is actually called 3 times after every keypress due to listening to multiple events, but the full update is only performed once per keypress. I've assumed that it checks to see if the text has changed from the last time the preview update was called, thus saving some processing.
    – Makyen Mod
    Commented Dec 8, 2018 at 23:37
  • I'll put it on my list of things to do to move a browser extension I hacked-up for myself into a userscript which is suitable for release. As it currently is, what I have certainly not perfect. I'd want to test it significantly with it in the page all the time, rather than just when I click a button. I'll probably want to make it adaptive wrt. delay too.
    – Makyen Mod
    Commented Dec 8, 2018 at 23:38
  • @Makyen check the below answer, you may find it useful. Commented Dec 31, 2018 at 13:48

1 Answer 1

10

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:

enter image description here

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:

enter image description here

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);
});
2
  • Nice. I wish you can earn reputation on meta. I would definitely award you a bounty for this. Commented Jan 1, 2019 at 0:23
  • seems fine :) was having a long answer recently : stackoverflow.com/a/54036270/8620333 and I didn't face issue. Commented Jan 4, 2019 at 15:41

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .