diff --git a/src/highlight.js b/src/highlight.js index 7974033794..946dafa817 100644 --- a/src/highlight.js +++ b/src/highlight.js @@ -819,8 +819,18 @@ const HLJS = function(hljs) { * auto-highlights all pre>code elements on the page */ function highlightAll() { + function boot() { + // if a highlight was requested before DOM was loaded, do now + highlightAll(); + window.removeEventListener('DOMContentLoaded', boot, false); + } + // if we are called too early in the loading process if (document.readyState === "loading") { + // make sure the event listener is only added once + if (!wantsHighlight) { + window.addEventListener('DOMContentLoaded', boot, false); + } wantsHighlight = true; return; } @@ -829,16 +839,6 @@ const HLJS = function(hljs) { blocks.forEach(highlightElement); } - function boot() { - // if a highlight was requested before DOM was loaded, do now - if (wantsHighlight) highlightAll(); - } - - // make sure we are in the browser environment - if (typeof window !== 'undefined' && window.addEventListener) { - window.addEventListener('DOMContentLoaded', boot, false); - } - /** * Register a language grammar module *