doufeikuang7724 2019-07-11 15:31
浏览 88

强制浏览器获取某些源的最新版本(CSS,JS等)[重复]

This question already has an answer here:

I would like, when someone is visiting my website, to make sure the browser has the last version of my files CSS, JS, etc. The idea I came with is to add an extra reference on my links:

Instead of using

<script type="text/javascript" src="www.mywebsite.com/my_file.js"><script>

I'm calling

<script type="text/javascript" src="www.mywebsite.com/my_file.js?lastUpdate"><script>

And i manage to replace lastUpdate by the date of the last modification of the file. The link becomes "new" and the browser is updating his cache regarding the file. Note that all my files are on my server.

To do so, I'm calling a php function (summarised)

function getLastUpdate($link){
    if(file_exists($link)){
        return $link.'?'.filetime($link);
    }
    return $link;
}

and call it :

echo '<script type="text/javascript" src="'.getLastUpdate('www.mywebsite.com/my_file.js').'"><script>';

Everything works. Almost. The function is stored in ./code/function.php And it is used by many files in many different folders. My problem : I don't know what to put for $link. Regarding the url address, it sometimes working, sometimes not. If I give absolute file-path (would be easier for me), the function file_exists returns false. If I give a relative path, it sometimes work, sometimes not. I guess due to the fact that I'm using an url-rewriting, and the link is changing ?

What am I doing wrong ? How should I solve this ? Thanks !

</div>
  • 写回答

1条回答 默认 最新

  • dongtong848825 2019-07-11 15:38
    关注

    I'm using that kind of code to always get the last version :

    Function:

    function file_versioning($file){
        $filemtime = filemtime($file);
        return "{$file}?v={$filemtime}";
    }
    

    Call of the function in "Core.php":

    $CssLib = file_versioning("{$IncDir}/Lib.css");
    // $IncDir is the relative path from the php script to the "library folder"
    echo <<<EOD
        <link rel="stylesheet" type="text/css" href="{$CssLib}" />
    EOD;
    

    Call of the "Core" in "index.php":

    $IncDir ='.inc/Libs';
    require $IncDir.'/Core.php';
    

    ⋅ ⋅ ⋅

    I don't know if that's the best way to do it… But well, that works. I can have multiple calls of the core at different places, but the relative path used by that core is written in each call script.

    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器