Search code examples
javascriptjquerywordpressperformancepagespeed

Run JavaScript after page load on WordPress using JQuery


I'm new to JS and I'm still trying to understand it all. So I've decided to give myself a few projects so I can learn the syntax.

I have a chat widget that loads when someone lands on my website. However, I'd like to only run this widget after the page has loaded to improve website performance.

How do I go about adjusting this script to run only after my WordPress web page has loaded?

<!--Start of Tawk.to Script-->
<script type="text/javascript">
var Tawk_API=Tawk_API||{}, Tawk_LoadStart=new Date();
(function(){
var s1=document.createElement("script"),s0=document.getElementsByTagName("script")[0];
s1.async=true;
s1.src='https://embed.tawk.to/...../default';
s1.charset='UTF-8';
s1.setAttribute('crossorigin','*');
s0.parentNode.insertBefore(s1,s0);
})();
</script>
<!--End of Tawk.to Script-->

UPDATED: The widget developer suggested this.

<!--Start of Tawk.to Script-->
<script type="text/javascript">
var w = window;
var Tawk_API=Tawk_API||{}, Tawk_LoadStart=new Date();
(function(){
function l() {
var s1=document.createElement("script"),s0=document.getElementsByTagName("script")[0];
s1.async=true;
s1.src='https://embed.tawk.to/...../default';
s1.charset='UTF-8';
s1.setAttribute('crossorigin','*');
s0.parentNode.insertBefore(s1,s0);
}
if (w.attachEvent) {
w.attachEvent('onload', l);
} else {
w.addEventListener('load', l, false);
}
})();
</script>
<!--End of Tawk.to Script-->

Solution

  • if you want it to load after the page has parsed add defer to the script tag

    <script type="text/javascript" defer>
    otherwise to load it after everything else call it on window load :

        window.onload = () => {
    
        var Tawk_API=Tawk_API||{}, Tawk_LoadStart=new Date();
            (function(){
            var s1=document.createElement("script"),s0=document.getElementsByTagName("script")[0];
            s1.async=true;
            s1.src='https://embed.tawk.to/...../default';
            s1.charset='UTF-8';
            s1.setAttribute('crossorigin','*');
            s0.parentNode.insertBefore(s1,s0);
            })();
    
        }