How to Use Defer and Async Javascript in WordPress: Speed Up Safely

Asynchronous JavaScript with "defer" and "async" is the key to solving the "render-blocking" problem and significantly increasing WordPress website speed. Proper application not only improves scores on Google PageSpeed Insights but also enhances user experience and retains visitors more effectively. This article will provide detailed instructions on the safest and most effective methods for you to confidently optimize your website.
Why is Defer and Async JavaScript important for WordPress speed?
Defer and async help eliminate render-blocking by JavaScript, allowing the browser to load HTML content in parallel with the script. This directly reduces page load times and improves Core Web Vitals scores.
Trong thiết kế web hiện đại, JavaScript đóng vai trò cốt lõi trong việc tạo ra các hiệu ứng động, xử lý biểu mẫu và tích hợp các dịch vụ bên thứ ba. Tuy nhiên, khi một trình duyệt web bắt đầu tải một trang, nó sẽ đọc mã HTML từ trên xuống dưới. Nếu gặp một thẻ <script> thông thường, trình duyệt bắt buộc phải dừng toàn bộ quá trình phân tích cú pháp HTML để tải xuống và thực thi đoạn mã đó. Quá trình tạm dừng này tạo ra một "nút thắt cổ chai" nghiêm trọng, khiến người dùng chỉ nhìn thấy một màn hình trắng tinh trong nhiều giây liền.
By using defer and async wordpress javascript, we are providing a clear directive to the browser: continue processing and displaying the visual interface to the user while the scripts are still being loaded in the background. At Pham Hai: Personal Blog, we realize that this is a basic technical step and brings the highest performance to optimize wordpress website speed. Understanding the nature of this process will help you master the performance of any website.
What is "Render-blocking JavaScript" and its impact on Core Web Vitals
Render-blocking JavaScript are script files that prevent the browser from rendering the interface until they are finished processing. Based on the latest updates as of March 2026, this severely impacts the LCP and INP metrics in the Core Web Vitals report.
The concept of Blocking rendering occurs when JS files force the browser to stop the construction of DOM (Document Object Model) and CSSOM. The direct consequence is that key performance metrics such as First Contentful Paint (FCP) and especially Large Contentful Paint (LCP) are significantly stretched. Users will feel that your website responds very slowly, negatively affecting the first impression.
In particular, according to Google's core updates, the Interaction to Next Paint (INP) index has officially and completely replaced First Input Delay (FID). Scripts that block display and occupy the main thread for too long are the leading reasons why a website's INP index exceeds the ideal level of 200ms. Thoroughly overcoming this error is not only a technical issue but also a solid foundation for you to conduct wordpress SEO optimization in a comprehensive and sustainable way, helping your website score absolutely in the eyes of search engines.
Detailed comparison of Defer and Async: When should you use which one?
"Async" loads and executes scripts immediately out of order, suitable for standalone scripts. "Defer" loads in the background but only executes when the HTML has finished parsing, ideal for scripts that depend on each other.
To compare async and defer javascript wordpress accurately, you need to understand the inner workings of each attribute through the page load lifecycle. The question of when to use async and defer in wordpress depends entirely on the specific functionality of that JS file on the website.
| Attributes | Detailed mechanism of action | Code execution order | Recommended application for practical use |
|---|---|---|---|
| Bình thường | Blocks HTML parsing to load and run instantly | Run in the exact order they appear in the source code | Minimize use, only use for extremely important scripts |
| Async | Tải không đồng bộ, chạy ngay khi tải xong mà không chờ HTML | The order is not guaranteed, the script that finishes downloading first will run first | Independent tracking scripts (Google Analytics, Facebook Pixel, Ads) |
| Defer | Tải trì hoãn, tải ngầm nhưng chỉ chạy khi DOM đã sẵn sàng | Make sure to run in the correct order in the HTML source code | Scripts control the interface, sliders, pop-ups, drop-down menus |
The biggest difference lies in execution time. Async can interrupt HTML parsing if it finishes loading early, while Defer always patiently waits for the HTML to be 100% complete before starting to run. If you have script files that depend on each other (for example, script A needs data from script B), using Async will cause fatal errors because file B may load slower than file A. In that case, Defer is the perfect savior.
Real-world benefits: Improved PageSpeed Insights scores and user experience (UX)
Applying defer/async removes the "Eliminate render-blocking resources" warning on Google PageSpeed Insights. As a result, the user experience (UX) is smoother, bounce rates are reduced, and WordPress SEO rankings are strengthened.
Ảnh hưởng của defer async đến pagespeed insights là vô cùng rõ rệt và có thể đo lường ngay lập tức. Khi bạn dời việc thực thi các tệp JavaScript nặng nề xuống sau khi giao diện đã hiển thị, điểm số hiệu suất trên thiết bị di động có thể tăng vọt từ 15 đến 30 điểm chỉ trong vài phút. Thuật toán của Google luôn ưu tiên các website có nội dung hiển thị (paint) nhanh chóng.
Besides, this optimization also combines extremely well with reduce HTTP requests and Minify JavaScript. When the source code is intelligently minified and loaded, the server system's load will be significantly reduced. A website with fast response time contributes greatly to enhanced user experience (UX). Customers will not have to wait annoyingly, thereby increasing the purchase conversion rate. If you are learning and applying methods to increase WordPress website speed, this is definitely a top priority technique that you cannot ignore.
Detailed instructions on how to add Defer and Async to WordPress

You can add defer and async using specialized speed optimization plugins or directly intervene in the source code through the functions.php file. Both methods are highly effective if done correctly.
There are many methods to implement defer and async javascript on the WordPress platform. Depending on your technical level and system management needs, you can choose one of the two paths below. We will share the two most popular ways: using plugins for beginners and using live code for developers. Each of these helps speed up WordPress with async defer safely and in compliance with the latest technical standards.
Method 1 (Recommended for newbies): Use Optimal Plugins
Plugins like LiteSpeed Cache, WP Rocket or Flying Scripts provide an intuitive interface to enable asynchronous loading with just a few clicks. This is the safest solution to avoid breaking the interface.
Using wordpress async defer javascript optimization plugin is the safest and most time-saving option for the vast majority of users. In the settings panel of popular plugins like WP Rocket, LiteSpeed Cache or Autoptimize, simply navigate to the "File Optimization" section and check the "Load JavaScript deferred" box.
These wordpress acceleration plugins are programmed to automatically analyze page structure and apply attributes to the entire source code without you having to write a single line of code. WP Rocket even offers "Safe Mode" for jQuery to ensure absolute safety. However, for the system to operate smoothly and maximize its power, you should combine it with other necessary wordpress plugins to manage caching and images. In addition, fast and smooth page loading speed also provides maximum support for best wordpress seo plugins to be effective in helping Google bots crawl more easily.
Method 2 (For advanced users): Edit functions.php file
Từ WordPress 6.3 trở lên, bạn có thể thêm thuộc tính này trực tiếp qua hàm wp_enqueue_script bằng cách truyền tham số strategy là defer hoặc async. Hoặc dùng filter script_loader_tag trong functions.php.
If you are a web developer or simply want to completely control how to embed async defer into wordpress theme without depending on third-party plugins that weigh down the website, intervene directly in the functions.php wordpress file. According to the latest updated WordPress technical documentation, adding async defer to wpenqueuescript is now greatly simplified.
Bạn chỉ cần thêm mảng $args chứa từ khóa strategy vào bên trong hàm wpenqueuescript. Cú pháp chuẩn sẽ trông như thế này:
wp_enqueue_script(
'my-custom-script',
get_template_directory_uri() . '/js/custom.js',
array(),
'1.0.0',
array( 'strategy' => 'defer' )
);
Nếu bạn đang bảo trì một hệ thống sử dụng phiên bản WordPress cũ hơn (trước 6.3), việc tận dụng hook action và filter trong wordpress thông qua filter script_loader_tag là cách tiếp cận chuẩn xác và mạnh mẽ nhất để chèn thêm thuộc tính vào thẻ script trước khi nó được xuất ra trình duyệt. Đoạn mã dưới đây sẽ tự động thêm defer vào tất cả các script ngoại trừ jQuery:
add_filter( 'script_loader_tag', 'add_defer_attribute', 10, 2 );
function add_defer_attribute( $tag, $handle ) {
if ( 'jquery' === $handle || is_admin() ) {
return $tag;
}
return str_replace( ' src', ' defer="defer" src', $tag );
}
Common errors when using Defer/Async and how to fix them safely
The most common error is interface breakage or loss of functionality due to dependent scripts (like jQuery) being loaded in the wrong order. Excluding core scripts from the defer/async process is the most radical fix.
In the process of providing services and supporting hundreds of customers, we often encounter defer async javascript wordpress errors and how to fix them, which sometimes requires patience in reviewing the source code. Applying this feature in bulk to all files without thorough testing can cause the website's layout to break or stop working completely.
Conflict error with jQuery and dependent scripts
When a script needs jQuery to run but jQuery is "deferred" and loaded later, the browser will report the error "jQuery is not defined". You are required to maintain the loading order of these platform libraries.
Many older generation themes and plugins in the WordPress ecosystem rely heavily on the jQuery wordpress library. When you force jQuery to defer, inline HTML snippets or small scripts that call jQuery immediately during page load will fail because the native library is not ready in memory. This error usually shows up as a red message "Uncaught ReferenceError: jQuery is not defined" in the Console tab of the browser.
Điều này trực tiếp dẫn đến việc các tính năng tương tác cốt lõi như menu thả xuống trên thiết bị di động, vòng lặp ảnh (image carousel), hay các nút bấm thêm vào giỏ hàng của WooCommerce không phản hồi khi người dùng nhấp vào. Giải pháp an toàn nhất để khắc phục tình trạng này là để tệp jQuery cốt lõi tải bình thường ở thẻ <head>, hoặc bạn phải đảm bảo tuyệt đối mọi script phụ thuộc vào nó đều được thiết lập defer đồng bộ một cách cẩn thận.
How to exclude important scripts from Defer/Async
In optimized plugins, you just need to paste the script's URL or filename into the "Exclude from Defer/Async" box. If using code, add an IF condition to ignore important handles.
Để chủ động phòng tránh các lỗi xung đột không đáng có, bạn cần lập một danh sách các tệp tin không được phép can thiệp. Trong giao diện cài đặt của hầu hết các plugin tối ưu tốc độ, luôn có sẵn một khu vực mang tên "Excluded JavaScript Files" (Loại trừ tệp JavaScript). Bạn chỉ cần copy và dán tên tệp (ví dụ: jquery.min.js, elementor-frontend.js hoặc woocommerce.min.js) vào hộp thoại này.
Nếu bạn là người thích code tay, hãy sử dụng câu lệnh điều kiện if ( in_array( $handle, array( 'jquery', 'core-script' ) ) ) return $tag; bên trong hàm callback của filter script_loader_tag. Điều này giúp hệ thống thông minh nhận diện và bảo vệ các chức năng lõi, trong khi vẫn tối ưu hóa được hàng chục tệp tin không quan trọng khác. Sự cẩn trọng này là chìa khóa để giữ cho website luôn ổn định.
Check and measure effectiveness after optimization
After setup, clear the WordPress Cache and use Google PageSpeed Insights to check again. It is necessary to ensure that the score increases and the website interface does not crash in incognito mode.
The final step that determines success or failure is that you must delete all WordPress Cache stored on the server as well as the cache on your personal browser. Then, open the website in an incognito window (Incognito Mode) and manually test every link, contact form, and button to make sure there are no Javascript error messages appearing in the Console tab of the Developer Tools tool.
Once everything is working perfectly, run the Google PageSpeed Insights tool again to accurately measure the improvement in page load times. Don't forget to combine CSS, HTML optimization (such as important inline CSS and source code compression) to achieve a comprehensive green score for the Core Web Vitals system, thereby affirming website quality in the eyes of search engines and surpassing competitors.
Optimizing JavaScript loading with defer and async is an essential technique to speed up your WordPress website. Whether you choose to use plugins to simplify the process or intervene in the code for greater control, the benefits in page load speed, SEO scores and user experience are undeniable. Start applying today to see a noticeable difference on your website.
Have you tried applying defer and async to your website? Please share your results or ask questions in the comments section below to discuss!
Note: The information in this article is for reference only. For the best advice, please contact us directly for specific advice based on your actual needs.