Dynamic URLs in CSS/JS

后端 未结 9 906
别跟我提以往
别跟我提以往 2021-02-05 16:14

I\'m splitting up one of my larger apps and introducing a \'cdn\' url to house common objects like CSS, javascript, and images to avoid duplication. What I need to do, though, i

相关标签:
9条回答
  • 2021-02-05 16:25

    When using relative URLs, you can force a "base" url. In the <head> tag, use <base href="http://cdn-dev.example.com">. Then, every relative link "/style.css" will point to "http://cdn-dev.example.com/style.css"

    For reference: http://www.w3schools.com/TAGS/tag_base.asp

    0 讨论(0)
  • 2021-02-05 16:29

    Depending on your server configuration, you can also append the .php-extension to your filenames and have them treated as PHP scripts too:

    I.E.: style.css.php would contain:
    
    .cool-button { background-image url(<?php echo $bgImgUrl;?>); }
    

    This also works for JavaScript-files.

    0 讨论(0)
  • 2021-02-05 16:32

    Use relative paths, not absolute paths. When inside a CSS file, the path is relative to the CSS file and not the HTML page.

    If your CSS file is here

    http://cdn.example.com/css/style.css
    

    And your class is

    .cool-button { background-image: url('../images/button.png'); }
    

    Then the browser will attempt to load the image from

    http://cdn.example.com/images/button.png
    
    0 讨论(0)
  • 2021-02-05 16:32

    Searching for an answer to this too, I saw a simple one: create your css file with duplicate classes, one for scenario 1 (images load from same domain) and another for scenario 2 (images load from CDN).

    e.g.

    .container {background-image:url(my/site/image.png;)}
    .container-CDN {background-image:url(http://my.site.cdn.com/image.png;)}
    

    Then on your index.php introduce PHP to call the correct class

    e.g.

    <body class="container<?PHP if ($whatever) {echo "-CDN";} ?>">
    
    0 讨论(0)
  • 2021-02-05 16:34

    Well...the solution I came up with was...sorta...hackish, ugly and dumb. But, hell, it worked:

    <?php
        if ($_SERVER['SERVER_NAME'] == "www.domain.tld") {
    
            $incs_path  = "/usr/local/psa/home/vhosts/domain.tld/non-web-root-folder/private-files";
    
        }
        else {
            $incs_path  = "incs";
        }
    
    require_once "$incs_path/$file-to-be-called.inc";
    
    ?>
    

    This is, as noted, hacky and ugly and could be done far more prettily. But it does, at least, allow you to define specific locations for specific groups of files depending on the host.

    0 讨论(0)
  • 2021-02-05 16:36

    If the server is same, you can use relative paths. Like /http/blah/test/images/button.png or ../images/button.png

    0 讨论(0)
提交回复
热议问题