脚本标签在加载DOM之前运行 [英] Script tag running before DOM is loaded

查看:40
本文介绍了脚本标签在加载DOM之前运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我相信脚本标签在加载DOM元素之前正在运行.我将如何等待首先加载元素?我试过将script标签的内容包装在 window.onload =()=>中.{} ,但没有运气.我也尝试过< body onload =''myFunc()''> .

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()">.

我的逻辑是,如果浏览器是Edge/IE,则将React内容隐藏在 root 中,并显示 unsupportedBrowser 内容,以使用户知道不支持此浏览器

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.

请注意,这仅在IE中发生.

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>

推荐答案

也许React给您带来了麻烦,因为当您包含它的源代码时,它仍然会执行.

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>

旁注:我不明白为什么您排除Edge浏览器.边缘!= Internet Explorer.如今,所有主流浏览器都支持标准浏览器API.为了与浏览器兼容,您还应该使用Babel将其下潜.

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.

这篇关于脚本标签在加载DOM之前运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆