How to Add a JS Script After Full Loading Checkout Page in Magento 2

checkoutmagento2script

Since the DOM on the checkout page is loaded in an asynchronous way – I do not have access to some elements. Please suggest me how we can add a custom script to the checkout page after loading all the elements.

Best Answer

To add javascript file in checkout page you should extend checkout_index_index.xml inside theme layout for magento checkout module or your custom module frontend layout folder, and add the following:

 <head>
   <link src="<url of your js file>"/>
 </head>

to wait until all the element loaded, you can check which element is the last one being rendered (example: .payment-method). Inside the javacript function you can make code to wait until this last element exists inside your js file:

require(['jquery', 'jquery/ui'], function($){ 
    $( document ).ready(function() {

      //wait until the last element (.payment-method) being rendered
      var existCondition = setInterval(function() {
       if ($('.payment-method').length) { 
        clearInterval(existCondition);
        runMyFunction();
       }
      }, 100);

      function runMyFunction(){
       console.log("Last");
      }

    }); 
 }); 
Related Topic