Dynamically load css stylesheet and wait for it to load

后端 未结 4 1618
失恋的感觉
失恋的感觉 2020-12-11 03:37

I have a script that detects a button click on which it will attach a CSS stylesheet to the "head" with jQuery like so:



        
4条回答
  •  一向
    一向 (楼主)
    2020-12-11 03:45

    You need to insert a link node in the head and then attach onload event to that. In your code link is a String. See sample code below on how to implement what you want.

    var link = document.createElement('link');
    link.setAttribute("rel", "stylesheet");
    link.setAttribute("type", "text/css");
    link.onload = CSSDone;
    link.setAttribute("href", 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css');
    document.getElementsByTagName("head")[0].appendChild(link);
    

    jsfiddle

提交回复
热议问题