From ddce857ca5730ea76815c08cc9c5cf3d8567396b Mon Sep 17 00:00:00 2001 From: Caleb Eggensperger Date: Tue, 27 Nov 2018 13:24:47 -0500 Subject: [PATCH] Use `DOMContentLoaded` instead of `unload` for initializing p5 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Documentation: https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded Quoth MDN: “A very different event load should be used only to detect a fully-loaded page. It is an incredibly common mistake to use load where DOMContentLoaded would be much more appropriate, so be cautious.” DOMContentLoaded is supported in all modern browsers, and can make a significant difference in page load performance when a page has many external assets, such as images and iframes. --- src/core/init.js | 4 ++-- src/core/main.js | 8 ++++++-- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/core/init.js b/src/core/init.js index 5eafd2b72b..9bf5672829 100644 --- a/src/core/init.js +++ b/src/core/init.js @@ -31,10 +31,10 @@ var _globalInit = function() { // TODO: ??? // if the page is ready, initialize p5 immediately -if (document.readyState === 'complete') { +if (document.readyState !== 'loading') { _globalInit(); // if the page is still loading, add an event listener // and initialize p5 as soon as it finishes loading } else { - window.addEventListener('load', _globalInit, false); + document.addEventListener('DOMContentLoaded', _globalInit, false); } diff --git a/src/core/main.js b/src/core/main.js index d36d81caeb..39e72e3f07 100644 --- a/src/core/main.js +++ b/src/core/main.js @@ -552,10 +552,14 @@ var p5 = function(sketch, node, sync) { if (sync) { this._start(); } else { - if (document.readyState === 'complete') { + if (document.readyState !== 'loading') { this._start(); } else { - window.addEventListener('load', this._start.bind(this), false); + document.addEventListener( + 'DOMContentLoaded', + this._start.bind(this), + false + ); } } };