簡體   English   中英

包含庫的最佳方式是什么?

[英]what is the best way to include libraries?

我正在嘗試創建一個移動輪播,我發現最好的方法是使用 jquery 移動庫,問題是當將它直接包含在模板中時,它會阻止渲染。

順便說一句,我正在使用 wordpress。

這就是為什么我的查詢是基於是否有任何好的做法來包含庫(在我的例子中是 jQuery Mobile)而不損壞負載/或頁面速度分數。

從已經非常感謝了!!!

您始終可以通過添加defer屬性來修改<script>標簽的 output。 這將使您的(JS)腳本非阻塞。

具有 defer 屬性的腳本將阻止 DOMContentLoaded 事件觸發,直到腳本加載並完成評估。 MDN

首先將您的wp_enqueue_scriptwp_enqueue_style包裝在wp_enqueue_scripts操作處理程序中。 這是注冊和排隊腳本和 styles WP Docs的正確方法。

add_action('wp_enqueue_scripts', function() {
  wp_enqueue_script('jqm_js', 'https://code.jquery.com/mobile/1.2./jquery.mobile-1.2.0.min.js', ['jquery'], '1.2.0');

  wp_register_style('jqm_css', 'https://code.jquery.com/mobile/1.2./jquery.mobile-1.2.0.min.css', [], '1.2.0');
  wp_enqueue_style('jqm_css',);
}, 10);

使用script_loader_tag過濾器,您可以修改<script>標記的生成方式。 如果句柄在$handles數組中,以下代碼片段將檢查每個已注冊和排隊的腳本。 如果是,那么它將在腳本中添加一個defer屬性。

修改$handles數組中的值以添加或刪除要延遲的任何腳本。

add_filter('script_loader_tag', function ($tag, $handle, $src) {
  $handles = ['jqm_js'];

  if (in_array($handle, $handles)) {
    $tag = str_replace(' src', ' defer="defer" src', $tag);
  }

  return $tag;
}, 10, 3);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM