使用 javascript 设置文档类型

bhb*_*bhb 4 html javascript doctype

我有一个没有 doctype 声明部署到服务器的 html 页面(比如 A)。这是从另一台服务器(比如 B)获取 js 文件。Node.js 创建必要的 html 页面来显示。现在 IE8 正在创建问题,因为没有声明 doctype(将自身设置为 IE5 quirks 模式)

现在 doctype 是读取的第一行,这似乎不可能通过这种方式完成(使用 js 设置 doctype)。是否可以设置元标记来将页面设置为标准模式?或者有没有其他我可以将页面设置为标准页面而无需修改来自服务器 A 的 html 页面。

S..*_*S.. 5

var nodeDoctype = document.implementation.createDocumentType(
 'html',
 '-//W3C//DTD XHTML 1.0 Transitional//EN',
 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtdd'
);
if(document.doctype) {
    document.replaceChild(nodeDoctype, document.doctype);
} else {
    document.insertBefore(nodeDoctype, document.childNodes[0]);
}
Run Code Online (Sandbox Code Playgroud)

根据您的评论更新:

可以使用 JS 更改文档类型以启用兼容性查看(如在此处完成:http : //www.webmasterworld.com/forum91/4856.htm)但这是一个非常讨厌的黑客,不推荐。理想情况下,您可以执行此服务器端。所以有一个 doctype js 参数,然后重新加载页面:

window.location = window.location+"?doctype=newdoctype"
Run Code Online (Sandbox Code Playgroud)

这将导致页面重新加载,这可能不适合您,但这是最安全的方法。

  • 浏览器会重新读取文档类型吗?html 页面已经加载。 (2认同)