JS:如果浏览器是IE,则显示某些div



我有一个react项目,它不能在IE中工作,我们不打算在IE中工作。

所以当渲染index.html时,通常会有root div来渲染react。

我不想渲染root div时,浏览器是IE,但不同的div,有一个消息警告,该应用程序不工作在IE

我可以知道如果浏览器是IE这样:

const isIE = !!window.MSInputMethodContext && !!document.documentMode

所以我试图改变htmldiv输出取决于isIE,我不太确定如何。

逻辑:

如果isIE - true渲染<div id="root"></div>

如果!isIE - false渲染<div>Browser not supported</div>

试过这样做:

<html>
<head>
<meta charset="utf-8" />
<% _.map(css, (item) => { %><link href="<%= item %>" rel="stylesheet"><% }) %>
</head>
<body>
<script>
const isIE = !!window.MSInputMethodContext && !!document.documentMode;
if (isIE) { document.getElementById('root').innerHTML += '<p>IE!!</p>' } // or something similar
</script>
<div id="root"></div>
<script>window.__ENVIRONMENT__ = Object.freeze(<%= JSON.stringify(environment) %>) 
</script>
<% _.map(js, (item) => { %><script src="<%= item %>"></script><% }) %>
</body>
</html>

还尝试了一个逻辑,将html作为字符串返回,如:

<script>
if (isIE) { return '<div>Browser not supported</div>'; }
else { return '<div id="root"></div> }
</script>

const IEdiv = '<div>This is IE</div>';
const rootDiv = '<div id="root"></div>';
if (isIE) { IEdiv.append('body'); }
else { rootDiv.append('body'); }

这个都不行

据我所知,React不应该在任何版本的IE上开箱即用。它需要(或者至少曾经需要)react-app-polyfill才能到达任何地方。

你也会遇到const的问题,因为它只支持IE11。如果你唯一关心的IE版本是IE11,你应该没有问题。


更新答案

我自己创建了一个样本,看看我能做什么。我第一次尝试用JS将<div>加载到页面中,并且在无法向文档添加元素时遇到了一个讨厌的IE错误。

所以我改变了我的方法回到你的-编辑现有的<div>。问题不在于您的代码,问题在于您的脚本在DOM(要访问)中出现<div>之前运行。将<div>置于脚本之上(或将JS移动到外部文件并加载它),它应该按照您的意愿工作。

这是我的示例供参考:

<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<div id="root"></div>
<script>
var isIE = !!window.MSInputMethodContext && !!document.documentMode;
console.warn(isIE);
if (isIE) { 
var root = document.getElementById('root');
root.innerHTML += 'IE!!';
}
else {
var root = document.getElementById('root');
root.innerHTML += 'hello hello hello';
// you may also need to defer React being loaded in
}
</script>
</body>
</html>

最新更新