动态地使用php包含css或Js文件 [英] Dynamically include css or Js file using php

查看:107
本文介绍了动态地使用php包含css或Js文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每次Gulp更改CSS或JS文件时,它都会保持输出文件名称与以前相同。浏览器如何知道文件已被更改,并需要重新加载css和JS文件?



要解决此问题,我决定使用以下Gulp插件:



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



它通过将内容哈希附加到文件名来重命名资产文件

  unicorn.css => unicorn-098f6bcd.css 

有没有办法使用php动态地包含资产文件?每次添加新内容时,资产名称都会发生变化。

解决方案

我发现了一种动态包含文件的方法。它的速度很快(大约需要1.5毫秒)并且工作完美。

PHP具有用于搜索文件的本地函数(glob)。根据PHP文档 glob()函数根据libc glob()函数使用的规则搜索匹配模式的所有路径名,这与常见shell使用的规则类似。

glob()

  // css路径将是您的css目录的完整物理路径
$ cssPath ='/css/*.css';
$ stylesheets = glob($ cssPath,GLOB_NOSORT);

//链接所有样式表
<?php foreach($ stylesheets as $ stylesheet):?>

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

<?php endforeach; ?>


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.

解决方案

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; ?>

这篇关于动态地使用php包含css或Js文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆