Dynamically include css or Js file using php

一个人想着一个人 提交于 2020-01-04 14:11:52

问题


Every time Gulp changes the CSS or JS files it keep the output file name same as before. How will browser know that file has been changed and need to reload the css and JS files?

To resolve this problem, I am decide to use the following Gulp plugin:

https://github.com/sindresorhus/gulp-rev

it rename the assets file by appending content hash to filenames

unicorn.css => unicorn-098f6bcd.css

is there any way to include the assets file using php dynamically? Assets name will change every time when new content added.


回答1:


instead renaming file, you can send finger print with it. if file changes, last modified changes too. so you can easily use file's last modified as finger print:

public function putStyle($fileName)
{
    $fp = filemtime($fileName); // finger print by file last modified
    $fileName .= '?' . $fp;
    echo '<link rel="stylesheet" href="' . $fileName . '"/>';
}



回答2:


I have found a way to include file dynamically. its fast (takes about 1.5 ms) and working perfectly.

PHP has a native function (glob) for searching files. According to PHP docs "The glob() function searches for all the pathnames matching pattern according to the rules used by the libc glob() function, which is similar to the rules used by common shells."

glob()

// css path would be the full physical path of your css directory
$cssPath = '/css/*.css';
$stylesheets = glob($cssPath, GLOB_NOSORT);

// link all stylesheets
<?php foreach($stylesheets as $stylesheet): ?>

     <link rel="stylesheet" href="css/<?=basename($stylesheet)?>">

<?php endforeach; ?>


来源:https://stackoverflow.com/questions/21719526/dynamically-include-css-or-js-file-using-php

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