How do I load css rules dynamically in Webkit (Safari/Chrome)?

后端 未结 8 1884
悲哀的现实
悲哀的现实 2020-12-10 17:16

I currently have issues in Webkit(Safari and Chrome) were I try to load dynamically (innerHTML) some html into a div, the html contains css rules (...), after the html gets

8条回答
  •  北荒
    北荒 (楼主)
    2020-12-10 17:23

    I think it's a better practice to append a "link" tag to the head of your document. If that isn't possible, try to append a "style" tag to the head. Style tags shouldn't be in the body (Doesn't even validate).

    Append link tag:

    var link = document.createElement('link');
    
    link.setAttribute('rel', 'stylesheet');
    
    link.type = 'text/css';
    
    link.href = 'http://example.com/stylesheet.css';
    
    document.head.appendChild(link);
    

    Append style tag:

    var style = document.createElement('style');
    
    style.innerHTML = 'body { background-color: #F00; }';
    
    document.head.appendChild(style);
    

提交回复
热议问题