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

麦子 优化维护9字数 1657阅读5分31秒阅读模式

由于我们在使用WordPress的时候会用到各种插件和主题,这样我们会看到很多的主题和插件都会有自带不少的JS代码,几十行JS代码也会占用前端页面的体积,我们是可以通过压缩合并JS来提高速度的。

  1. //JS代码合并
  2. add_action( 'wp_enqueue_scripts', 'merge_all_scripts', 9999 );
  3. function merge_all_scripts()
  4. {
  5. global $wp_scripts;
  6. /*
  7. #1. Reorder the handles based on its dependency,
  8. The result will be saved in the to_do property ($wp_scripts->to_do)
  9. */
  10.  
  11. $wp_scripts->all_deps($wp_scripts->queue);
  12. $merged_file_location = get_stylesheet_directory() . DIRECTORY_SEPARATOR . 'merged-script.js';
  13. $merged_script = '';
  14. // Loop javascript files and save to $merged_script variable
  15. foreach( $wp_scripts->to_do as $handle)
  16. {
  17. /*
  18. Clean up url
  19. */
  20.  
  21. $src = strtok($wp_scripts->registered[$handle]->src, '?');
  22. /**
  23. #2. Combine javascript file.
  24. */
  25.  
  26. // If src is url http / https
  27. if (strpos($src, 'http') !== false)
  28. {
  29. // Get our site url
  30. $site_url = site_url();
  31. /*
  32. If we are on local server, then change url to relative path
  33. */
  34.  
  35. if (strpos($src, $site_url) !== false)
  36. $js_file_path = str_replace($site_url, '', $src);
  37. else
  38. $js_file_path = $src;
  39. /*
  40. To be able to use file_get_contents function we need to remove slash
  41. */
  42.  
  43. $js_file_path = ltrim($js_file_path, '/');
  44. }
  45. else
  46. {
  47. $js_file_path = ltrim($src, '/');
  48. }
  49. // Check wether file exists then merge
  50.  
  51. if (file_exists($js_file_path))
  52. {
  53. // #3. Check for wp_localize_script
  54.  
  55. $localize = '';
  56.  
  57. if (@key_exists('data', $wp_scripts->registered[$handle]->extra)) {
  58.  
  59. $localize = $obj->extra['data'] . ';';
  60. }
  61.  
  62. $merged_script .= $localize . file_get_contents($js_file_path) . ';';
  63. }
  64. }
  65. // write the merged script into current theme directory
  66.  
  67. file_put_contents ( $merged_file_location , $merged_script);
  68. // #4. Load the URL of merged file
  69.  
  70. wp_enqueue_script('merged-script', get_stylesheet_directory_uri() . '/merged-script.js');
  71. // 5. Deregister handles
  72.  
  73. foreach( $wp_scripts->to_do as $handle )
  74. {
  75. wp_deregister_script($handle);
  76. }
  77. }

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

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