Cinna Cinna - 2 years ago 69
HTML Question

document.getElementById sometimes null despite using window.onload

I am having an issue where document.getElementById is sometimes (one time in 10-20) returning null despite using window.onload. My relevant code is below.


<div msa-include-html="msa.html"></div>
<script type="text/javascript" src="msa.js"></script>
<script type="text/javascript">
<script type="text/javascript">
window.onload = function () {


<form id="msa" method="get">
<input id="input" type="text" name="input" />
<p id="output"></p>
<input id="btn" type="submit" value="SUBMIT" />


includeHTML = function (cb) {
var z, i, elmnt, file, xhttp;
z = document.getElementsByTagName("*");
for (i = 0; i < z.length; i++) {
elmnt = z[i];
file = elmnt.getAttribute("msa-include-html");
if (file) {
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
elmnt.innerHTML = this.responseText;
}"GET", file, true);
if (cb) cb();

function initForm(urlAction) {
document.getElementById("msa").action = urlAction;
document.getElementById("input").addEventListener("keyup", updateOutput);

function updateOutput() {
var input = document.getElementById("input").value;
var output = Number((1 / 3 * input).toFixed(0));
document.getElementById("output").innerHTML = output.toLocaleString();

Many thanks in advance.

Answer Source

Your includeHTML() function performs an asynchronous operation to fetch content. The function will return after starting that operation, but the fetch will finish after your other code expects the content it loads to be present in the DOM.

The line

if (cb) cb();

should be inside the XHR callback, not outside as you've got it now. As it stands now, the callback will be invoked before the HTTP request completes. Your code only works when the content is in the browser cache, I suspect.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download