在< head>之后包含CSS的正确方法
问题描述:
显然,在文档正文中添加< link rel =stylesheet...
被W3C标准视为不良做法。在主体中添加< style>
块也是如此...
Apparently adding <link rel="stylesheet" ...
in the document body is considered a bad practice by W3C standards. The same for adding <style>
blocks in the body...
解决方案在< head>
标签之外添加CSS?
So are there any standard-compliant solutions to add CSS outside of the <head>
tag? Like at the end of the document.
答
如果您只想在特定事件中包含CSS样式,你这样做的头:
If you only want to include your CSS styles on a specific events, there's nothing stopping you from doing so at the head:
var linkElement = document.createElement("link");
linkElement.rel = "stylesheet";
linkElement.href = "path/to/file.css"; //Replace here
document.head.appendChild(linkElement);
这增加了以异步方式添加样式表的额外好处,从下载任何其他内容。
This has the added benefit of adding your stylesheet in an async way, which doesn't block the browser from downloading anything else.