注册脚本/样式:可以通过插件定制版本查询字符串吗?

时间:2013-02-05 作者:Gabriel Luethje

扩展标题中的问题:

我想找到一种方法(通过插件)为输出的JS和CSS文件版本查询字符串使用时间戳wp_register_stylewp_register_script.

我知道这可以在调用本身中轻松修改,目前我是这样做的:

$style_mtime = filemtime(dirname(__FILE__) . \'/css/style.css\');
wp_register_style( \'fstop-stylesheet\', get_stylesheet_directory_uri() . \'/library/css/style.css\', array(), $style_mtime , \'all\');
wp_enqueue_style( \'fstop-stylesheet\' );
如果我能将时间戳部分传递到插件中,我会很高兴的。我最近发现了这个插件,它可以很好地将查询字符串移动到文件名中,从而可以更好地缓存代理:https://gist.github.com/ocean90/1966227

它确实工作得很好。我想添加时间戳位来自动化整个过程。

想法?

1 个回复
SO网友:webaware

旧答案(基于您想要缓存拦截器的误解):您可以使用add_query_arg() 它添加/替换查询参数。

<?php
/**
* Plugin Name: wpse_84670
* Version: 0.0.1
* Description: replace script/style version with time as a cache buster
*/

/**
* replace script or stylesheet version with current time
* @param  string $url the source URL
* @return string
*/
function wpse_84670_time_as_version($url) {
    return add_query_arg(array(\'ver\' => time()), $url);
}

add_filter(\'script_loader_src\', \'wpse_84670_time_as_version\');
add_filter(\'style_loader_src\', \'wpse_84670_time_as_version\');
新答案:不要那样做!它将强制对页面上每个排队的脚本和样式表进行文件访问,这取决于您激活的插件,这可能意味着每次访问页面/帖子都会额外访问十几个或更多的文件。其中许多甚至不会导致浏览器请求这些文件(如果为脚本和样式表配置的时间已过期,那么应该!)

相反,只需在主题的排队代码周围包装一个函数,以便只对主题排队的文件进行文件访问。

更好的是,在你的主题中保留一个滚动版本号(在我的主题中,我称之为$forceLoad) 并将其用作传递给wp\\u enqueue\\u脚本的版本。不需要额外的文件访问权限。

$forceLoad = \'42\';
wp_enqueue_style(\'fstop-stylesheet\', get_stylesheet_directory_uri() . \'/library/css/style.css\', false, $forceLoad, \'all\');

结束

相关推荐