泪雪网改版也有二十多天了,子凡也是在努力的完善一些功能,这不我的强迫症有犯了,对于折腾和追求极致的道路是越陷越深。

在我们优化站点时一大核心思想就是“按需/动态加载”,PHP功能代码、jQuery特效或CSS样式,最理想的状态都是:当前页面需要时才加载进来,当前页面加载的都是必需的。这样才能达到我们页面的最小冗余升至没有冗余,这是对于一个追求极致的程序员所必须的。

wordpress-dribbble-plugin-icons

WordPress3.6版本增加了一个新的函数 has_shortcode(),这个函数的主要功能就是检测指定内容里是否存在指定的Shortcode使用,带来的好处就是只在有使用指定 Shortcode 的文章页面才载入相关脚本文件,这样细微的纠结虽然不能给页面载入带来直观的载入速度提升,但好的习惯总能带来不错的效果的。喜欢极致的人就继续看吧!

1
2
3
4
5
6
7
8
9
10
11
12
//文章按需加载Shortcode相关文件
function fanly_shortcode_scripts(){
	global $post;
	if( has_shortcode( $post->post_content, 'your-shortcode') ){//'your-shortcode'为你的短代码
		wp_register_style(	'shortcode_style',	get_template_directory_uri().'/style.css',	'',	'',	'all'	);//基于调用主题根目录下的style.css
		wp_register_script(	'shortcode_js',	get_template_directory_uri().'/js.js',	'',	'',	true	);//js加载到底部
 
		wp_enqueue_style( 'shortcode_style' );//检测到有使用短码后加载css文件
		wp_enqueue_script( 'shortcode_js');//检测到有使用短码后加载js文件
	}
}
add_action( 'wp_enqueue_scripts', 'fanly_shortcode_scripts');

当然,如果你还没能有升级到3.6版本以后,那么这里在提供一种方法吧!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//文章按需加载Shortcode相关文件(兼容3.6以前版本)
function fanly_shortcode_scripts(){
	global $post;
	wp_register_style(	'shortcode_style',	get_template_directory_uri().'/style.css',	'',	'',	'all'	);//基于调用主题根目录下的style.css
	wp_register_script(	'shortcode_js',	get_template_directory_uri().'/js.js',	'',	'',	false	);//js
	if( function_exists('has_shortcode') AND has_shortcode( $post->post_content, 'your-shortcode') ){
		wp_enqueue_style( 'shortcode_style' );//检测到有使用短码后加载css文件
		wp_enqueue_script( 'shortcode_js');//检测到有使用短码后加载js文件
	}else{
		wp_enqueue_style( 'shortcode_style' );//检测到有使用短码后加载css文件
		wp_enqueue_script( 'shortcode_js');//检测到有使用短码后加载js文件
	}
}
add_action( 'wp_enqueue_scripts', 'fanly_shortcode_scripts');

这样做的目的就是为了给还在使用WordPress 3.6以前版本的兼容,其实也算不上是兼容,无非就是变成直接加载,而不是按需加载了。

代码参考:WPJAM 感谢!

更多关于WordPress优化及疑问可以添加QQ群:255308000

除非注明,否则均为泪雪博客原创文章,禁止任何形式转载

本文链接:https://zhangzifan.com/wp-enqueue-script-when-has-shortcode.html

留言评论

登录 后留言