作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
所以,直到今天我才写过 php,我正在尝试在一个 WordPress 网站上实现一个缓存破坏系统,该网站中有一些 React 组件。所以在 footer-home.php
文件里面我有这个:
</div> <?php // close #app ?>
</main>
<div class="container footer">
<div class="row">
<div class="col-sm-12">
<div id="instagram"></div>
</div>
</div>
<?php get_footer('shared') ?>
</div>
</div><?php //close container ?>
<?php
function grab_hashed_bundle_script() {
$path = '/client/';
$fileName = null;
$dirJS = new DirectoryIterator($path);
foreach ($dirJS as $file) {
if (pathinfo($file, PATHINFO_EXTENSION) === 'js') {
$fileName = basename($file);
break;
}
}
return $fileName;
}
$bundle_js = grab_hashed_bundle_script();
?>
<script src="/client/<?php echo $bundle_js ?>"></script>
<?php wp_footer(); ?>
</body>
</html>
我知道这是丑陋的 AF 和 hacky,所以如果有人能指出更好的方法来做到这一点,我洗耳恭听。
我需要这样做的原因是,每次我们运行新的构建时,我都会让 webpack 添加一个随机的 6 位哈希值到 bundle.js 文件名(如 bundle-123456.js
中)。以前,我们在此页脚文件中只有一个常规脚本标记,如下所示: <script src=/client/bundle.js"></script>
但即使在我们更新之后,客户的浏览器最终也会缓存bundle.js,要求客户必须清空缓存才能获取新的 .js 文件。
非常感谢任何帮助。
此外,我并没有尝试按照评论中的建议使用参数缓存半身像。我试图根据随机散列进行破坏,我让 webpack 在构建时将其插入到 bundle.js 文件的名称中。
最佳答案
这是我的一位同事提出的解决方案:
functions.php 内部:
/**
* Grab Hashed Bundle Files
*/
function enqueue_hashed_bundle_files() {
// soooo gross. would love to know of a cleaner way.
$build_dir = get_theme_root() . '/../../../client/build/';
$all_files = scandir($build_dir);
$css_files = array();
$js_files = array();
foreach( $all_files as $file ){
$pathinfo = pathinfo($file);
switch( $pathinfo['extension'] ){
case 'js':
array_push($js_files, $file);
break;
case 'css':
array_push($css_files, $file);
break;
default:
break;
}
}
// now that we have the filenames, we can access them directly with the
// absolute url
$base_url = get_option('siteurl') . '/client/';
wp_enqueue_script( 'bundlejs', $base_url . $js_files[0], array(), null, true );
wp_enqueue_style( 'bundlecss', $base_url . $css_files[0], array(), null );
}
关于javascript - 如何在 WordPress 站点内使用 PHP 来查找散列的 bundle.js 文件并将适当的文件名插入到脚本标记中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45112417/
我是一名优秀的程序员,十分优秀!