Jquery add css to head

前端 未结 2 531
别那么骄傲
别那么骄傲 2020-12-15 06:35

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.



        
相关标签:
2条回答
  • 2020-12-15 07:23

    This will place the new link after the last link already in your head element.

    $("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:

    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.

    0 讨论(0)
  • 2020-12-15 07:31

    you can use:

    .prepend()

    http://api.jquery.com/prepend/

    0 讨论(0)
提交回复
热议问题