change css link and wait till new css is loaded

前端 未结 6 505
南笙
南笙 2020-12-17 22:48

I wonder whether it\'s possible to change stylesheet link of the loaded document, then wait till the new css is loaded, and then run appropriate js code

thanks for a

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-17 22:57

    @ahren had it almost correct. However using a callback when the css file is finished loading via dynamically changing the href on a link element DOES NOT seem to work on most mobile devices.

    Instead try directly injecting the style into a style element using load .. ends up being supported by most modern browsers including mobile ones

    UPDATED to include support for IE 8- ; NOTE this requires you to inject a dummy rule into your css to verify when the css is loaded (in this case use body {ready:true;})

    css

    body {ready:true;}
    ...
    

    html

    
    

    javascript

    if (document.createStyleSheet) {
    
        //Wait for style to be loaded
        var wait = setInterval(function(){
          //Check for the style to be applied to the body
          if($('body').css('ready') === 'true') {
            clearInterval(wait);
    
            //CSS ready
          }
        }, 300);
    
        document.createStyleSheet(url);
    } else {
        //Dynamically load the css for this doc
        $("#your-style-element").load(url,function(){
    
           //CSS ready
        });
    }
    

提交回复
热议问题