简体   繁体   中英

Add JS and CSS files on IF/ELSE in html

Here is situation

in Dev Environemt , I have to add css and js file like below

<script src="../../js/file.js">
<link rel="stylesheet" type="text/css" href="../../css/file.css">

in Production Environment , I have to add same css and js file like below with the change in src attribute

<script src="js/file.js">
<link rel="stylesheet" type="text/css" href="css/file.css">

Any solution to do it dynamically instead of manually

Thanks

You can use PHP for that.

On the import / include, use <?php echo dirname(dirname($_SERVER['PHP_SELF'])); ?> <?php echo dirname(dirname($_SERVER['PHP_SELF'])); ?>

EG:

<link rel="stylesheet" type="text/css" href="<?php echo dirname(dirname($_SERVER['PHP_SELF'])); ?>/css/style.css">

dirname($_SERVER['PHP_SELF']) will return the path to the current file's directory.

dirname(dirname($_SERVER['PHP_SELF'])); will return the path before the current file's directory. You can read more about that here , and about $_SERVER['PHP_SELF'] here .

About using PHP , click here .

You can achieve that creating the style and script tag on the fly according to an IF.

    var link = document.createElement('link');
    link.setAttribute('rel', 'stylesheet');
    link.setAttribute('type', 'text/css');
    if (production)
        link.setAttribute('href', 'css/my.css');
    else
        link.setAttribute('href', 'css/dev_my.css');
    document.getElementsByTagName('head')[0].appendChild(link);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM