From 57c3cae5abd5c796b093ad02661b040b2c877fc4 Mon Sep 17 00:00:00 2001
From: Stephen Blott
Date: Sat, 2 Apr 2016 12:12:19 +0100
Subject: Refactor DomUtils.documentReady.
We do not need to install separate event listeners for every callback.
Just install one listener and keep track of the callbacks ourself.
This is clearer, and also determines the order in which callbacks are
called. (Although, we don't rely on that currently.)
This also adds a tests.
---
lib/dom_utils.coffee | 18 +++++++++---------
tests/dom_tests/dom_tests.html | 2 ++
tests/dom_tests/dom_utils_test.coffee | 12 ++++++++++++
3 files changed, 23 insertions(+), 9 deletions(-)
diff --git a/lib/dom_utils.coffee b/lib/dom_utils.coffee
index 3fc08b78..9a6c1b09 100644
--- a/lib/dom_utils.coffee
+++ b/lib/dom_utils.coffee
@@ -3,15 +3,15 @@ DomUtils =
# Runs :callback if the DOM has loaded, otherwise runs it on load
#
documentReady: do ->
- isReady = false
- (callback) ->
- if document.readyState == "loading" and not isReady
- window.addEventListener "DOMContentLoaded", handler = ->
- isReady = true
- window.removeEventListener "DOMContentLoaded", handler
- callback()
- else
- callback()
+ [isReady, callbacks] = [document.readyState != "loading", []]
+ unless isReady
+ window.addEventListener "DOMContentLoaded", onDOMContentLoaded = ->
+ window.removeEventListener "DOMContentLoaded", onDOMContentLoaded
+ isReady = true
+ callback() for callback in callbacks
+ callbacks = null
+
+ (callback) -> if isReady then callback() else callbacks.push callback
createElement: (tagName) ->
element = document.createElement tagName
diff --git a/tests/dom_tests/dom_tests.html b/tests/dom_tests/dom_tests.html
index ab48a88a..d2e795d1 100644
--- a/tests/dom_tests/dom_tests.html
+++ b/tests/dom_tests/dom_tests.html
@@ -32,6 +32,8 @@
+
+
diff --git a/tests/dom_tests/dom_utils_test.coffee b/tests/dom_tests/dom_utils_test.coffee
index ce8fa370..98c7cc8d 100644
--- a/tests/dom_tests/dom_utils_test.coffee
+++ b/tests/dom_tests/dom_utils_test.coffee
@@ -1,3 +1,15 @@
+context "DOM content loaded",
+
+ # The DOM content has already loaded, this should be called immediately.
+ should "call callback immediately.", ->
+ called = false
+ DomUtils.documentReady -> called = true
+ assert.isTrue called
+
+ # See ./dom_tests.html; the callback there was installed before the document was ready.
+ should "already have called callback embedded in test page.", ->
+ assert.isTrue window.documentReadyListenerCalled? and window.documentReadyListenerCalled
+
context "Check visibility",
should "detect visible elements as visible", ->
--
cgit v1.2.3