Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional include of CSS

Tags:

javascript

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");
like image 286
Joel Avatar asked Feb 04 '11 16:02

Joel


1 Answers

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>
like image 144
Arnaud Le Blanc Avatar answered Sep 20 '22 10:09

Arnaud Le Blanc