Jquery 将 css 添加到头部
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12093509/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Jquery add css to head
提问by Deac Karns
I am asynchronously adding a few scripts and style sheets to a project that I am building and would like to keep the style sheets all grouped together in the HEAD.
我正在向我正在构建的项目中异步添加一些脚本和样式表,并希望将样式表全部分组在 HEAD 中。
<head>
<title>home</title>
<meta charset="utf-8">
<link rel="Shortcut Icon" type="image/ico" href="/img/favicon.png">
<!-- STYLES-->
<link rel="stylesheet" href="/css/fonts-and-colors.css" type="text/css" media="screen">
<link rel="stylesheet" href="/css/layout.css" type="text/css" media="screen">
<!-- JS-->
<script type="text/javascript" async="" src="/js/light-box.js"></script>
<script type="text/javascript" src="/js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="/js/grade-button.js"></script>
<script>
$(document).ready(function() {
// some code
});
</script>
<link rel="stylesheet" href="/css/masterBlaster.css" type="text/css" media="screen">
</head>
I am currently using
我目前正在使用
$("head").append("<link rel='stylesheet' href='/css/masterBlaster.css' type='text/css' media='screen'>");
which works fine, but it adds it to the bottom of my HEAD section as you can see in the example.
效果很好,但正如您在示例中看到的那样,它将它添加到我的 HEAD 部分的底部。
The OCD in me would like to add it either before my first style link or after the last style link.
我的强迫症想在我的第一个样式链接之前或最后一个样式链接之后添加它。
Thanks for looking.
谢谢你看。
回答by Curt
This will place the new link
after the last link
already in your head
element.
这会将新link
的link
放在head
元素中的最后一个之后。
$("head link[rel='stylesheet']").last().after("<link rel='stylesheet' href='/css/masterBlaster.css' type='text/css' media='screen'>");
However if you don't already have a link
in place this won't add the new link
. Therefore you should do a check first:
但是,如果您还没有link
就位,则不会添加新的link
. 因此,您应该先进行检查:
var $head = $("head");
var $headlinklast = $head.find("link[rel='stylesheet']:last");
var linkElement = "<link rel='stylesheet' href='/css/masterBlaster.css' type='text/css' media='screen'>";
if ($headlinklast.length){
$headlinklast.after(linkElement);
}
else {
$head.append(linkElement);
}
The OCD in me would like to add it either before my first style link or after the last style link.
我的强迫症想在我的第一个样式链接之前或最后一个样式链接之后添加它。
You should decide where exactly the link
is going to be placed. Theres a chance a different position might override existing styles.
您应该决定link
将要放置的确切位置。不同的位置可能会覆盖现有的样式。