In some cases, you want to run your own scripts inside of Piano templates, but the scripts are not able to read HTML content that not been rendered on your website.
It's possible that our templates are being rendered sooner than the website's content and thus the script runs before the HTML element is available. As the script has to work with those elements, when they are not visible, they don’t technically exist yet and the script doesn't run.
Therefore, it's necessary to wait for the elements to be rendered and then run the script. Below are 2 options on how to achieve this.
-
You can try using the JavaScript equivalent of the document ready function. For example like this:
HTML<script> // self executing function here (function() { // your page initialization code here // the DOM will be available here })(); </script>This will wait for the DOM to be loaded and then it will run the JS inside. We recommend for this to be tested for your specific use case and inside your particular iframe.
-
You can also search for an element over and over until it gets loaded. Once it's detected, you would be running your script. For this, you can use the function
setInterval. For example:HTML<div custom-script> const repeatContentCheck = setInterval(function(){ if(document.querySelector('button.pn-offer-list__subscribe')){ //YOUR CODE clearInterval(repeatContentCheck); // if executed clear interval } }, 200); </div>In the above snippet, the script searches every 200 milliseconds to check if the element is yet available. If it's not, it starts the search again and again, until the element is available. If it is, it runs your JavaScript once and then clears the interval to stop the loop from executing.