一組代碼實現WordPress壓縮合并JS減小頁面體積提速

麥子 優(yōu)化維護40字數 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);
  }
}

這里,在網上找到一段這個代碼可以實現,但是有些時候會有可能導致有些功能失效,所以我們根據實際情況添加。

投上你的一票
 
  • 本文由 麥子 發(fā)表于 2024年9月26日 08:35:14
  • 轉載請務必保留本文鏈接:http://bjj.org.cn/compress-wpjs.html