一组代码实现WordPress压缩合并JS减小页面体积提速

老乐 优化维护1字数 1657阅读5分31秒阅读模式

由于我们在使用WordPress的时候会用到各种插件和主题,这样我们会看到很多的主题和插件都会有自带不少的JS代码,几十行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);
  }
}

这里,在网上找到一段这个代码可以实现,但是有些时候会有可能导致有些功能失效,所以我们根据实际情况添加。

投上你的一票
 
  • 本文由 老乐 发表于 2024年9月26日 08:35:14
  • 转载请务必保留本文链接:https://www.zhujipingjia.com/compress-wpjs.html
  • WordPress压缩代码