无需WordPress插件合并站点中JS脚本 减少页面体积的方法

前几天,麦子有整理到HTML代码如何压缩降低页面的体积,同时还有很多插件有实现的办法可以将页面中多个JS代码合并和压缩,这里我也在找找网上有没有整理过的方法,尤其是无插件实现的。这里找到一个可以且实现的JS代码合并的方法,但是没有压缩功能,这里先整理过来以后有需要再修改。

//JS代码合并
add_action( 'wp_enqueue_scripts', 'merge_all_scripts', 9999 );
function merge_all_scripts() 
{
	global $wp_scripts;
	
	/*
		#1. Reorder the handles based on its dependency, 
			The result will be saved in the to_do property ($wp_scripts->to_do)
	*/

	$wp_scripts->all_deps($wp_scripts->queue);	
	
	$merged_file_location = get_stylesheet_directory() . DIRECTORY_SEPARATOR . 'merged-script.js';
	
	$merged_script	= '';
	
	// Loop javascript files and save to $merged_script variable
	foreach( $wp_scripts->to_do as $handle) 
	{
		/*
			Clean up url
		*/

		$src = strtok($wp_scripts->registered[$handle]->src, '?');
		
		/**
			#2. Combine javascript file.
		*/

		// If src is url http / https
		
		if (strpos($src, 'http') !== false)
		{
			// Get our site url
			$site_url = site_url();
		
			/*
				If we are on local server, then change url to relative path
			*/

			if (strpos($src, $site_url) !== false)
				$js_file_path = str_replace($site_url, '', $src);
			else
				$js_file_path = $src;
			
			/*
				To be able to use file_get_contents function we need to remove slash
			*/

			$js_file_path = ltrim($js_file_path, '/');
		}
		else 
		{			
			$js_file_path = ltrim($src, '/');
		}
		
		// Check wether file exists then merge

		if  (file_exists($js_file_path)) 
		{
			// #3. Check for wp_localize_script

			$localize = '';

			if (@key_exists('data', $wp_scripts->registered[$handle]->extra)) {

				$localize = $obj->extra['data'] . ';';
			}

			$merged_script .=  $localize . file_get_contents($js_file_path) . ';';
		}
	}
	
	// write the merged script into current theme directory

	file_put_contents ( $merged_file_location , $merged_script);
	
	// #4. Load the URL of merged file

	wp_enqueue_script('merged-script',  get_stylesheet_directory_uri() . '/merged-script.js');
	
	// 5. Deregister handles

	foreach( $wp_scripts->to_do as $handle ) 
	{
		wp_deregister_script($handle);
	}
}

这个代码添加到 Functions.php 功能中,然后我们可以看到前端JS代码都只合并成一个 merged-script.js 这样使得JS文件数量减少,如果再能压缩就更好。这个以后再看看如何实现,实在不行就要巴拉已有的插件看看如何实现的。类似的插件还是有很多的。

投票 post
© 版权声明
THE END
喜欢就支持一下吧
点赞10 分享