Search code examples
phpjavascriptcssdynamic-data

Dynamic CSS and Javascript


How does one create Dynamic CSS and JavaScript On-The-Fly (using PHP). This needs to be done as different pages have different set of elements sometimes, so wrapping and sending a large CSS/JS everytime would be overkill. And why do many sites have link tags like this:

<link rel='stylesheet' type='text/css' href='css/style.css?pg_id=43&post=62'>

How does the CSS come to know the GET parameters?

Since this might involve URL rewriting or using the header function, please supply short examples


Solution

  • So, there's a few different approaches you can take here. First, if you have access to apache's virtualhost files, you can set CSS to be read by a php interpreter. I've never done this and wouldnt exactly recommend it but an example is:

    <VirtualHost *:80>
      AddType application/x-httpd-php .css
    </VirtualHost>
    

    This can also be done in your .htaccess file.

    Alternatively, you can make a link like

    <link rel='stylesheet' type='text/css' href='css/style.php?pg_id=43&post=62'>
    

    and put

    <?php header("Content-type: text/css"); ?>
    

    as the first line.

    I've never considered Vinicius' technique but I don't doubt that has its own set of advantages and disadvantages too.

    PS - sometimes GET variables are uses for caching purposes (or actually to prevent caching by appending the current unix timestamp to the css link with php like

    <link href="style.css?<?php echo time()" type="text/css" rel="stylesheet" />