0

I have a script in my phtml file but I want to only load this ones the page is fully loaded. I am doing a check if my custom module is enabled show the < script >

Adding script like this :

You can achieve this using template call

<referenceContainer name="before.body.end">
        <block class="Magento\Framework\View\Element\Template" template="Namespace_Modulename::before.phtml" name="before_body_js"/>
</referenceContainer>

Can anyone give me a advice or help to figure this out

<script>
document.getElementById("demo").innerHTML = "My First JavaScript";
</script>

I have to use this as well

<script type="text/javascript">
  alert("This alert box was called with the onload event");
</script>

2 Answers 2

1

If it's a script, you can try wrapping your script code inside

$( document ).ready(function() {
 // Your code
});

This will ensure that your code written inside will be reflected once the page is loaded.

1
  • I have added a script in my question this is what I am trying to add Commented Aug 23, 2020 at 11:59
1

domReady! - You can use this feature of the RequireJS like the native Magento's modules use:

<script>
    //<![CDATA[
    require(
        [
            'jquery',
            'domReady!'
        ], function($) {
            // Your Code
        });
    //]]>
</script>

DOMContentLoaded - Executes after DOM is loaded (before img and css):

document.addEventListener("DOMContentLoaded", function(){
    document.getElementById("demo").innerHTML = "My First JavaScript";
});

load - Executes after everything is loaded and parsed:

window.addEventListener("load", function(){
    document.getElementById("demo").innerHTML = "My First JavaScript";
});
7
  • I have updated the question with the script I am trying to pass. Commented Aug 23, 2020 at 12:00
  • Please check updated answer.
    – Pratik Oza
    Commented Aug 23, 2020 at 12:21
  • I have added one more script can I still use the same method? Commented Aug 23, 2020 at 12:53
  • Yes you can add.
    – Pratik Oza
    Commented Aug 23, 2020 at 13:05
  • How would I do that please can you show me Commented Aug 23, 2020 at 13:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.