Reputation: 91
I was setting up a very simple page to populate a dropdown list from an array on DOMContentLoaded Event, however in my environment (VS code + live Server extension), I was getting an error because the entire body object didn't exist at the moment of DOMContentLoaded which was strange to me .
I read a few sites online but they did indicate that DOMContentedLoaded and readyState of interactive was interchangeable aside from older browser support. https://caniuse.com/#search=DOMContentLoaded https://developer.mozilla.org/en-US/docs/Web/API/Document/readyState
So I explored it and it seems that if I call an anonymous function in my browser (with the same function call in it) it will have a ready state of "interactive" but if I just call the function directly, it will have a ready state of "loading." Now in codpen.io and in Stacks Snippets it even renders fine, but in my local environment it will error and ultimately shouldn't the ready state be interactive regardless?
The document I linked talked about broader support by using the document.onreadychange and I guess for my specific situation I would go that route but I wanted to ask to see if if anyone else has encountered this? I am on Chrome Version 67.0.3396.99 (Official Build) (64-bit), tested on Chrome, Firefox and Opera with the same results.
function DomLoaded(element) {
console.log("Looking for " +element + " | current document state:" + document.readyState);
var typelist = document.getElementById(element);
listofTypes.forEach(function(currentvalue, index) {
var option = document.createElement("option");
option.text = currentvalue;
typelist.add(option);
});
}
var listofTypes = ["accounting", "airport", "amusement_park", "aquarium"];
document.addEventListener("DOMContentLoaded", function() {
DomLoaded("typelistanonfunc");});
document.addEventListener("DOMContentLoaded", DomLoaded("typelist"));
<html>
<head>
<title>Document Load</title>
</head>
<body>
<h1 id="header1">Test 1</h1>
<select id="typelist" style="max-width: 90%;"></select>
<select id="typelistanonfunc" style="max-width: 90%;"></select>
</body>
</html>
Upvotes: 0
Views: 1491
Reputation: 413720
Here:
document.addEventListener("DOMContentLoaded", DomLoaded("typelist"));
you are calling the DomLoaded()
function and passing the (undefined
) return value to addEventListener()
. That will happen before the "ready" event is fired, and the error you get will be due to the target <select>
element not being in the DOM yet.
An expression like something(somethingElse)
is a function call. It is evaluated immediately in all cases.
The first form:
document.addEventListener("DOMContentLoaded", function() { DomLoaded("typelist"); });
is correct. The function expression created around the call to your handler is not a function call; it's just a reference to that anonymous function. That will correctly create an event handler for the "ready" (DOMContentLoaded
) event.
Upvotes: 2