I have used
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<button type="button" id="button">Click</button>
<pre id="output">Not Loading...</pre>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.17.0/babel.min.js"></script>
<script type="text/babel">
document.addEventListener('DOMContentLoaded', function () {
const button = document.getElementById('button');
const output = document.getElementById('output');
output.textContent = 'Loading...';
addEventListener('click', function () {
output.textContent = 'Done';
});
});
</script>
</body>
</html>
but it seems the code inside document.addEventListener('DOMContentLoaded', function () {});
is not loading.
If I remove this from my code, it suddenly works.
I have made a JS Bin here.
Another option would be to use the
readystatechange
event. Thereadystatechange
event fires when thereadyState
attribute of thedocument
has changed. ThereadyState
attribute can be one of the following three values:'loading'
,'interactive'
, or'complete'
. An alternative to using theDOMContentLoaded
event is to look for thereadyState
to equal'interactive'
inside of thedocument
'sreadystatechange
event, as in the following snippet.Although, in your case, the
document
'sreadyState
seems to have already reached'complete'
. In that case, you can simply swap'interactive'
for'complete'
in the snippet above. This is technically equal to theload
event instead of theDOMContentLoaded
event.Read more on MDN, Document.readyState Document: readystatechange event
It's most likely because the
DOMContentLoaded
event was already fired at this point. The best practice in general is to check for document.readyState to determine whether or not you need to listen for that event at all.The event has already fired by the time that code hooks it. The way Babel standalone works is by responding to
DOMContentLoaded
by finding and executing all of thetype="text/babel"
scripts on the page. You can see this in theindex.js
file:Just run the code directly, without waiting for the event, since you know Babel standalone will wait for it for you.
Also note that if you put you script at the end of the body, just before the closing
</body>
tag, there's no need to wait forDOMContentLoaded
even if you don't use Babel. All of the elements defined above the script will exist and be available to your script.In a comment you've asked:
Just ensure that your
script
tag is at the end ofbody
as described above, and there's no need to use the event.If it's important to you to use it anyway, you can check to see whether the event has already run by checking
document.readyState
(after following the link, scroll up a bit):document.readyState
goes through these stages (scroll up slightly from the link above):Thanks to Ruslan & here is the full code snippet with the convenient detach of the
DOMContentLoaded
handler after it is used.