首页>技术知识>WordPress WordPress网站合并站点中JS脚本 减少页面体积的教程方法
WordPress教程学习网站
2022-04-09
WordPress教程学习网站丨模板定制、网站使用教程、插件推荐、代码优化、wp建站教程、数据文章采集、系统开发、系统优化,功能开发,仿站教程等各类WordPress技术知识,供网友学习了解。

WordPress网站合并站点中JS脚本 减少页面体积的教程方法,其实wp网站有很多插件是可以实现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文件数量减少,如果再能压缩就更好。这个以后再看看如何实现,实在不行就要巴拉已有的插件看看如何实现的。类似的插件还是有很多的。

显示全部内容...