使用jquery向未知页面添加CSS节点

Adding a CSS node into unknown pages using jquery

本文关键字:添加 CSS 节点 jquery 未知 使用      更新时间:2023-09-26

如何使用jquery将<link>节点添加到页面的<head>部分?如果元素已经存在,则不应该添加两次。

我需要添加这个CSS文件,因为它为我的搜索函数引入了额外的样式。这个jquery荧光笔需要.highlight类被添加到页面,所以高光看起来是黄色的。

Edit:我可以这样做,但是它不会检查元素是否已经添加。

$('head').append('<link rel="stylesheet" href="style2.css" type="text/css" />');

详细信息在实时演示的源代码中进行了注释:PLUNKER和下面的代码片段:

/* This script can be placed before the closing </body> tag as is or wrapped in a declared function then called. (ex. function init() {....}) */
// Reference the <head>
var head = document.getElementsByTagName('head')[0];
// This will find a `('link` element with a `[href` attribute with the value ending `$=` with `"style2.css"` `]')`
var style2 = document.querySelector('link[href$="style2.css"]');
// create a <link>
var link = document.createElement('link');
// Add a href attribute with the value of "style3.css" to the new <link>
link.href = 'style3.css';
// Add a rel attribute with the value of 'stylesheet'
link.setAttribute('rel', 'stylesheet');
// If <link href='style2.css'... already exists, then quit, else add the new <link> as the last child of the <head> 
var inject = (style2) ? false : head.appendChild(link);
return inject;
<!doctype html>
<html>
  <head>
    <link hraf='style.css' rel='stylesheet'>
    <link href='style2.css' rel='stylesheet'>
    </head>
  <body>
    <p>Use devtools and find the &lt;head&gt;. You should see the following*:</p>
      <pre><code>
  &lt;head&gt;
    &lt;link rel="stylesheet" href="style1.css"&gt;
    &lt;!--link rel="stylesheet" href="style2.css"--&gt;
    &lt;link rel="stylesheet" href="style3.css"&gt;
  &lt;/head&gt;
       </code></pre>
       *The code displayed above is always green.
      <script src="init.js"></script><!--script wrapped in a declared function in an external js file-->
    <script>
      init(); //Call init() right before the body closing tag or place the whole script here without being wrapped in a declaritive function.
    </script>
  </body>
</html>

该脚本将在加载时运行,不依赖于jQuery。