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.
-
I suppose you have added through document ready and element is not accessible right? in that case, just for the workaround you can use the setTimeout and check for the ID of that element exist if found then add your code inside that if the condition. let me know if my assumption is wrong.– Ashish RanadeCommented Mar 29, 2018 at 10:04
2 Answers
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");
}
});
});
-
adding js is recommended using the
data-mage-init
attribute or using the<script type="text/x-magento-init" />
tag devdocs.magento.com/guides/v2.2/javascript-dev-guide/javascript/… Commented Jun 6, 2018 at 9:00 -
This is not a proper solution. You are adding 100ms time delay function and if somehow checkout components loads slower then it will not work. Commented Sep 21, 2021 at 2:00
you can use hideLoader method in your js component
hideLoader: function() {
//your code here
},