How to load a CSS file based on a URL or client?

﹥>﹥吖頭↗ 提交于 2021-01-28 11:55:52

问题


I have two CSS files in my Sencha touch application. Lets call them A.css and B.css. Based on the URL I want the application to load different CSS.

Lets say URL 1 is www.website.com/#1 so for this I would like to load A.css. similarly URL 2 is www.website.com/#2 so for this I would like to load B.css

Is it possible to load CSS dynamically based on the URL?


回答1:


You can use JavaScript Regex for this.

Very easy method:

    // For www.website.com/#1
    if (/www.website.com\/#1/.test(window.location.href)) {
        /* Your Code Here For Loading Css */
    }

    // For www.website.com/#2
    if (/www.website.com\/#1/.test(window.location.href)) {
        /* Your Code Here For Loading Css */
    }

I hope this helps!!!




回答2:


You can use the follow JavaScript code to load CSS dynamically for your requirement:

if (window.location == "http://www.website.com/#1") {
     LoadCSS("A.css")
}
else if(window.location == "http://www.website.com/#2") {
     LoadCSS("B.css")
}

function LoadCSS(filename) {
     var fileref = document.createElement("link");
     fileref.setAttribute("rel", "stylesheet");
     fileref.setAttribute("type", "text/css");
     fileref.setAttribute("href", filename);
}



回答3:


Get hashtag value from URL and then depending on value change the link for CSS.

To get hashtag value:

$url = "www.website.com/#1";
$params = parse_url($url);

$value = $params['fragment'];

This will give you hashtag value, then depending on value link CSS file in header:

<?php if ($value == 1) { ?>
<link href="A.css" rel="stylesheet" type="text/css" />
<?php } else { ?>
<link href="B.css" rel="stylesheet" type="text/css" />
<?php } ?>



回答4:


I assume you have one template available for 2 URLs. Loading CSS using JavaScript is a pretty bad practice because it's slow and it's giving the user a bad experience since nothing is initially styled.

Anyway you can use the append function to add the CSS to the head tag.

$('head')
  .append( $('<link rel="stylesheet" type="text/css" />')
  .attr('href', 'your_stylesheet_url') );

And for the URL itself simply use the JavaScript window.location like so:

if (window.location == "#1url") {
    // load the A.css using the append function like above
}


来源:https://stackoverflow.com/questions/24860029/how-to-load-a-css-file-based-on-a-url-or-client

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!