{"id":3016,"date":"2023-11-14T12:32:20","date_gmt":"2023-11-14T05:32:20","guid":{"rendered":"https:\/\/dev.artru.net\/?p=3016"},"modified":"2023-11-14T14:58:13","modified_gmt":"2023-11-14T07:58:13","slug":"delay-javascript-theo-tuong-tac-nguoi-dung","status":"publish","type":"post","link":"https:\/\/artru.net\/en\/delay-javascript-theo-tuong-tac-nguoi-dung\/","title":{"rendered":"Delay Javascript according to user interaction"},"content":{"rendered":"<p>If someone asked me how to improve website load times and key metrics in Google Speed Lighthouse, I would answer &quot;Delay all unnecessary Javascript files&quot;.<\/p>\n\n\n\n<p>Today, I will share with you the benefits of Delay Javascript and how you can implement it on your website.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Benefits of Delaying Javascript<\/h2>\n\n\n\n<p>This results in huge improvements to important web metrics such as:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>First Contentful Paint<\/li>\n\n\n\n<li>Total Blocking Time (&amp; First Input Delay)<\/li>\n\n\n\n<li>Time to Interactive<\/li>\n<\/ul>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"976\" height=\"523\" src=\"https:\/\/cdn.artru.eu.org\/wp-content\/uploads\/2023\/11\/Discover-what-your-real-users-are-experiencing.png\" alt=\"Discover what your real users are experiencing\" class=\"wp-image-3035\"\/><figcaption class=\"wp-element-caption\">Discover what your real users are experiencing<\/figcaption><\/figure>\n<\/div>\n\n\n<p>You can also defer third-party scripts used for tracking such as GA4, Facebook Pixel, etc. However, I do not recommend deferring these scripts, as it will distort your statistical data. Friend.<\/p>\n\n\n\n<p>So that is the trade-off we need to make, the index will not be able to reach 100%. The alternative to achieving 100% is to use Cloudflare&#039;s tracking, the downside is that the parameters are not as detailed as others.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Async, Defer, Delay<\/h2>\n\n\n\n<p>Most websites have used Async and Defer to improve page load times and performance scores, but the increase is not significant.<\/p>\n\n\n\n<p>Let&#039;s first look at the code snippets to understand the differences in how each technique is implemented.<\/p>\n\n\n\n<pre class=\"wp-block-code\" data-no-translation=\"\" data-no-auto-translation=\"\"><code data-no-translation=\"\" data-no-auto-translation=\"\">Normal Load\n&lt;script src=\"script.js\">&lt;\/script>\n\nAsync\n&lt;script async src=\"script.js\">&lt;\/script>\n\nDefer\n&lt;script defer src=\"script.js\">&lt;\/script>\n\nDelay\n&lt;script delay=\"script.js\">&lt;\/script><\/code><\/pre>\n\n\n\n<p><code data-no-translation=\"\" data-no-auto-translation=\"\">&lt;script delay=\"script.js\">&lt;\/script><\/code> is not an official HTML attribute. It only serves as a placeholder. I will use Javascript delay code instead <code data-no-translation=\"\" data-no-auto-translation=\"\">delay = src<\/code> when there is user interaction.<\/p>\n\n\n\n<p>When using attribute <strong>async <\/strong>, it will load the script in parallel with parsing the page and then execute it as soon as the script loads.<\/p>\n\n\n\n<p>When using attribute <strong>defer <\/strong>, it loads the script in parallel with parsing the page but only executes after the page has finished loading.<\/p>\n\n\n\n<p>As you might guess, <strong><strong>defer <\/strong><\/strong>is a much better choice than <strong>async<\/strong>. You can find a detailed comparison between both in this article by <a href=\"https:\/\/flaviocopes.com\/javascript-async-defer\/\" target=\"_blank\" rel=\"noreferrer noopener\">Flavio Copes<\/a>.<\/p>\n\n\n\n<p>There are methods <strong>delay. delay<\/strong>, due to missing attributes <strong>src<\/strong> so the browser won&#039;t load the script. So it also gives good performance and scores.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Doing<\/h2>\n\n\n\n<p>If you are using WordPress, there are already a number of plugins available that can implement this feature out of the box. But if you are passionate about writing code without using plugins or using drag-and-drop builders, you can refer to option 2.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">For WordPress websites<\/h3>\n\n\n\n<p>The following plugins provide the Delay JavaScript feature:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/wordpress.org\/plugins\/flying-scripts\/\" target=\"_blank\" rel=\"noreferrer noopener\">Flying Scripts<\/a> (Free of charge)<\/li>\n\n\n\n<li><a href=\"https:\/\/wordpress.org\/plugins\/litespeed-cache\/\" target=\"_blank\" data-type=\"link\" data-id=\"https:\/\/wordpress.org\/plugins\/litespeed-cache\/\" rel=\"noreferrer noopener\">LiteSpeed Cache<\/a> (Free of charge)<\/li>\n\n\n\n<li><a href=\"https:\/\/wp-rocket.me\/\" target=\"_blank\" rel=\"noreferrer noopener\">WP-Rocket<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/flyingpress.com\/\" target=\"_blank\" rel=\"noreferrer noopener\">FlyingPress<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/perfmatters.io\/\" target=\"_blank\" rel=\"noreferrer noopener\">Perfmatters<\/a><\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Delay Javascript with code<\/h3>\n\n\n\n<p>Here is the code I use to Delay Javascript. The best place to place this code is at the bottom, specifically the footer.<\/p>\n\n\n\n<pre class=\"wp-block-code\" data-no-translation=\"\" data-no-auto-translation=\"\"><code data-no-translation=\"\" data-no-auto-translation=\"\">const autoLoadDuration = 5; \/\/In Seconds\nconst eventList = &#91;\"keydown\", \"mousemove\", \"wheel\", \"touchmove\", \"touchstart\", \"touchend\", \"scroll\"];\n\nconst autoLoadTimeout = setTimeout(runScripts, autoLoadDuration * 1000);\n\neventList.forEach(function(event) {\n    window.addEventListener(event, triggerScripts, { passive: true })\n});\n\nfunction triggerScripts() {\n    runScripts();\n    clearTimeout(autoLoadTimeout);\n    eventList.forEach(function(event) {\n         window.removeEventListener(event, triggerScripts, { passive: true });\n    });\n}\n\nfunction runScripts() {\n    document.querySelectorAll(\"script&#91;delay]\").forEach(function(scriptTag) {\n        scriptTag.setAttribute(\"src\", scriptTag.getAttribute(\"delay\"));\n    });\n}<\/code><\/pre>\n\n\n\n<p>Explanation: the above code will search all scripts <code data-no-translation=\"\" data-no-auto-translation=\"\">&lt;script><\/code> has attributes <code data-no-translation=\"\" data-no-auto-translation=\"\">delay<\/code> and replace it with <code data-no-translation=\"\" data-no-auto-translation=\"\">src<\/code> when there is user interaction (key press, mouse click, mouse move, scroll, touch, swipe) or after 5 seconds.<\/p>\n\n\n\n<p>2 variables <code data-no-translation=\"\" data-no-auto-translation=\"\">autoLoadDuration<\/code> and <code data-no-translation=\"\" data-no-auto-translation=\"\">eventList<\/code> You can specify it to your own liking.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">These files defer safely<\/h2>\n\n\n\n<p>The following are file categories that I recommend you defer to. However, you still have to make sure that everything is working as it should before deployment.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Advertising scripts (Google Adsense, Amazon Ads, Taboola, Outbrain, Media.net,...).<\/li>\n\n\n\n<li>Embed follow and like buttons on social networks.<\/li>\n\n\n\n<li>Live chat (Zendesk, Customerly, Intercom, tawk.to, Olark,...).<\/li>\n\n\n\n<li>Third-party scripts (Disqus Comments, Facebook Comments, Cookie Consent, etc.)<\/li>\n\n\n\n<li>Script is not needed to display above-the-fold content.<\/li>\n<\/ul>\n\n\n\n<p>To be more certain, you need to carefully check the delayed files in Devtools to see if it affects the user experience.<\/p>","protected":false},"excerpt":{"rendered":"<p>N\u1ebfu ai \u0111\u00f3 h\u1ecfi t\u00f4i l\u00e0m c\u00e1ch n\u00e0o \u0111\u1ec3 c\u1ea3i thi\u1ec7n th\u1eddi gian t\u1ea3i trang web v\u00e0 c\u00e1c ch\u1ec9 s\u1ed1 quan tr\u1ecdng trong Google Speed Lighthouse, t\u00f4i s\u1ebd tr\u1ea3 l\u1eddi [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[9],"tags":[],"class_list":["post-3016","post","type-post","status-publish","format-standard","hentry","category-website"],"_links":{"self":[{"href":"https:\/\/artru.net\/en\/wp-json\/wp\/v2\/posts\/3016","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/artru.net\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/artru.net\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/artru.net\/en\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/artru.net\/en\/wp-json\/wp\/v2\/comments?post=3016"}],"version-history":[{"count":0,"href":"https:\/\/artru.net\/en\/wp-json\/wp\/v2\/posts\/3016\/revisions"}],"wp:attachment":[{"href":"https:\/\/artru.net\/en\/wp-json\/wp\/v2\/media?parent=3016"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/artru.net\/en\/wp-json\/wp\/v2\/categories?post=3016"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/artru.net\/en\/wp-json\/wp\/v2\/tags?post=3016"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}