Script tag running before DOM is loaded
I believe the script tag is running before the DOM elements are loaded. How would I go about waiting for the elements to be loaded first? I’ve tried wrapping the script tag’s content in window.onload = () => {}
but no luck. I’ve also tried <body onload="myFunc()">
.
My logic is to hide the React content in root
if the browser is Edge/IE and show the unsupportedBrowser
content to let the user know that this browser is not supported.
Note this only happens in IE.
<html> <body> <div id="root">React Content</div> <div id="unsupportedBrowser" style="display: none;"> Microsoft Edge is NOT supported. </div> <script type="text/javascript" defer> document.addEventListener("DOMContentLoaded", function(){ if (window.document.documentMode || window.navigator.userAgent.indexOf("Edge") > -1) { alert("Edge browser"); document.getElementById("root").style.display = "none"; //ERROR here, rest doesn't run document.getElementById("unsupportedBrowser").style.display = "block"; // do other things }; }); </script> </body> </html>
Answer
Maybe React is giving you a hard time, since it gets still executed when you include the source for it.
<html> <body> <script type="text/javascript"> document.addEventListener("DOMContentLoaded", function(){ if (window.navigator.userAgent.indexOf("Edge") > -1) { alert("Edge browser"); document.body.innerHTML = '<div id="unsupportedBrowser" style="display: none;">Microsoft Edge is NOT supported.</div>' }else{ var root = document.createElement("div"); root.setAttribute("id", "root"); document.body.appendChild(root); var react_script = document.createElement("script"); react_script.setAttribute("src", "your_script"); document.body.appendChild(react_script); } }); </script> </body> </html>
A side note: I don’t get why you exclude the Edge browser. Edge != Internet Explorer. These days all major browser support the standard browser APIs. For browser compatibility you should also use Babel to transpile it down.