Magento 2 Module


How to move the Javascript files to the footer in Magento 2


Hide/Show description

Hello, My name is Cuong, I'm a Magento Developer, Welcome back to my Magento 2 tutorial video series. #magento2tutorial #magento2training #magento2 Today, I am going to show everybody the best practice, How to move the Javascript files to the footer in Magento 2. Why do you need to move the Javascript files to the footer of a website? It helps to speed up your website and reduce the initial load time of your page. When you test the speed of a website by some tools such as PageSpeed Insights of Goole or Gtmetrix.com, you will be required to eliminate render-blocking JavaScript files. Let's see this we check the website https://magento.com The files are preventing the page from loading as fast as possible. To resolve this issue, you need to move all the Javascript to the footer. Include the inline Javascript in HTML and the Javascript files. By default, Magento 2 loads all the javascript files in the head. You can check it on the storefront. We will move all these to the footer. So what will we do in this practice? 1. We will create a new module called PHPCuong_DeferParsingOfJavascript 2. We will use the event named controller_front_send_response_before to move all the Javascript to the footer before rendering the content of the page. Okie, let's go. So let's move all the Javascript to the footer you need to complete the following steps by step: Step 1: Declaring the new module called PHPCuong_DeferParsingOfJavascript - Create the namespace PHPCuong in the path app\code - Create the module named DeferParsingOfJavascript in the path app\code\PHPCuong - Create the file named registration.php in the path app\code\PHPCuong\DeferParsingOfJavascript - Create the file named module.xml in the path app\code\PHPCuong\DeferParsingOfJavascript\etc End of step #1, I have been completed the codes to create the new module called PHPCuong_DeferParsingOfJavascript. Step 2: Subscribing to the event named controller_front_send_response_before You can see this event name here. - Create the new file named events.xml in the path app\code\PHPCuong\DeferParsingOfJavascript\etc\frontend - Create the new file named DeferJS.php in the path app\code\PHPCuong\DeferParsingOfJavascript\Observer Step 3: Test and See the results 1. Run the following command lines: php bin/magento setup:upgrade --keep-generated php bin/magento cache:flush 2. Go to the storefront. Yeah, It works perfectly. Thanks for watching the guide. If you have any questions about this practice, please feel free to leave a comment below. Don't forget to like, comment, share my videos and subscribe to my channel for getting the latest lessons. Please do not hesitate to contact me, if you need me to join your Magento project. My rate is $25/hour in Magento 1 and $30/hour in Magento 2. Get the source code of this tutorial in the Github https://github.com/php-cuong/magento2-defer-parsing-of-javascript