Conditional include of CSS

2020-08-21 04:08发布

问题:

Is there a way I can use Javascript to include a CSS file only if the top frame URL contains the string "facebook.com"?

Short pseudo code:

if top.frame.url.contains("facebook.com"):
   include("style-facebook.css");

回答1:

A quick document.write-based solution would be:

<script type="text/javascript">
    if (/facebook\.com/.test(window.top.location.host)) {
        document.write('<link rel="stylesheet" type="text/css" href="stylefacebook.css" />');
    }
</script>

Or using the dom:

<script type="text/javascript">
    if (/facebook\.com/.test(window.top.location.host)) {
        var lnk = document.createElement('link');
        lnk.type='text/css';
        lnk.href='stylefacebook.css';
        lnk.rel='stylesheet';
        document.getElementsByTagName('head')[0].appendChild(lnk);
    }
</script>

Or with jquery:

<script type="text/javascript">
    if (/facebook\.com/.test(window.top.location.host)) {
        $('head:first').append('<link rel="stylesheet" type="text/css" href="stylefacebook.css" />');
    }
</script>


回答2:

<script type="text/javascript">
//<![CDATA[
if ("condition is satisfied") {
    if (document.createStyleSheet) {
        document.createStyleSheet('http://server/style-facebook.css');
    } else {
        var styles = "@import url(' http://server/style-facebook.css ');";
        var newSS = document.createElement('link');
        newSS.rel = 'stylesheet';
        newSS.href = 'data:text/css,' + escape(styles);
        document.getElementsByTagName("head")[0].appendChild(newSS);
    }
}
//]]>
</script>


标签: javascript