How to determine if CSS has been loaded?

后端 未结 4 878
青春惊慌失措
青春惊慌失措 2020-12-01 09:28

How can i Assert that the CSS for a page has successfully loaded and applied its styles in Watin 2.1?

4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-01 10:12

    Since browser compatibility can vary, and new future browser standards subject to change, I would recommend a combination of the onload listener and adding CSS to the style sheet so you can listen for when the HTML elements z-index changes if you are using a single style sheet. Otherwise, use the function below with a new meta tag for each style.

    Add the following to the CSS file that you are loading:

    #*(insert a unique id for he current link tag)* {
        z-index: 0
    }
    

    Add the following to your script:

    function whencsslinkloads(csslink, whenload ){
        var intervalID = setInterval(
            function(){
                if (getComputedStyle(csslink).zIndex !== '0') return;
                clearInterval(intervalID);
                csslink.onload = null;
                whenload();
            },
            125 // check for if it has loaded 8 times a second
        );
        csslink.onload = function(){
            clearInterval(intervalID);
            csslink.onload = null;
            whenload();
        }
    }
    

    Example

    index.html:

    
    
        
            
            
        
        
            CSS Loaded: no
        
    
    

    script.js:

    function whencsslinkloads(csslink, whenload ){
        var intervalID = setInterval(
            function(){
                if (getComputedStyle(csslink).zIndex !== '0') return;
                clearInterval(intervalID);
                csslink.onload = null;
                whenload();
            },
            125 // check for if it has loaded 8 times a second
        );
        csslink.onload = function(){
            clearInterval(intervalID);
            csslink.onload = null;
            whenload();
        }
    }
    /*************************************/
    whencsslinkloads(
        document.getElementById('EpicStyleID'),
        function(){
            document.getElementById('result').innerHTML = ''
        }
    )
    

    the_style.css

    #EpicStyleID {
        z-index: 0
    }
    

    PLEASE do not make your script load synchronously (without the async attribute) just so you can capture the link's onload event. There are better ways, like the method above.

提交回复
热议问题