How to load CSS using jquery

前端 未结 4 1578
孤独总比滥情好
孤独总比滥情好 2020-12-05 03:52

I have loaded a css file on server so I am having a URL with me. How can i load it in my perl code using JQuery ?

So currently I am hardcoding the css in my mason pa

相关标签:
4条回答
  • 2020-12-05 04:17
    $(document).ready(function(){
        console.log("ready!");
    var e=$("<link>",{
        rel:"stylesheet",
        type:"text/css",
        href:"/your/css/file.css"})[0];
    e.onload=function(){
    console.log("CSS IN IFRAME LOADED")},
    document.getElementsByTagName("head")[0].
    appendChild(e)});
    
    0 讨论(0)
  • 2020-12-05 04:35

    I like being consistent about language and file type (ex: don't mix css with html). So I would go for creating a style.css file and loading it into a tag with jQuery.

    index.html

    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    </head>
    <body>
        <div>
            <style id="import"></style>
            <h2 class="red">this is red</h2>
        </div>
        <script type="text/javascript">
            $( document ).ready(function() {
                $( "#import" ).load( "./style.css" );
            });
        </script>
    </body>
    </html>
    

    style.css

    .red{
        color: red;
    }
    
    0 讨论(0)
  • 2020-12-05 04:38

    I don't get why you can not just insert the <link/> element in the <head/> section, but here's a jQuery snippet:

    $('head').append( $('<link rel="stylesheet" type="text/css" />').attr('href', 'your stylesheet url') );
    
    0 讨论(0)
  • 2020-12-05 04:40

    Again, as per Dynamically loading css stylesheet doesn't work on IE.

    You need to set the href attr last and only after the link elem is appended to the head:

    $('<link>')
      .appendTo('head')
      .attr({
          type: 'text/css', 
          rel: 'stylesheet',
          href: '/css/your_css_file.css'
      });
    
    0 讨论(0)
提交回复
热议问题