javascript - document.getElementById sometimes null despite using window.onload -
i having issue document.getelementbyid (one time in 10-20) returning null despite using window.onload. relevant code below.
ptp.html:
<body> <div msa-include-html="msa.html"></div> <script type="text/javascript" src="msa.js"></script> <script type="text/javascript"> includehtml(); </script> <script type="text/javascript"> window.onload = function () { initform("urlaction"); } </script> </body> msa.html:
<form id="msa" method="get"> <input id="input" type="text" name="input" /> <p id="output"></p> <input id="btn" type="submit" value="submit" /> </form> msa.js:
includehtml = function (cb) { var z, i, elmnt, file, xhttp; z = document.getelementsbytagname("*"); (i = 0; < 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; elmnt.removeattribute("msa-include-html"); includehtml(cb); } } xhttp.open("get", file, true); xhttp.send(); return; } } 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 in advance.
your includehtml() function performs asynchronous operation fetch content. function return after starting operation, fetch finish after other code expects content loads present in dom.
the line
if (cb) cb(); should inside xhr callback, not outside you've got now. stands now, callback invoked before http request completes. code works when content in browser cache, suspect.
Comments
Post a Comment