For a restaurant website I need to work with a booking module that is a pain to load.
It takes a whopping 4 seconds to load it's script and that's on the 380mb/s ethernet connection I get to work on. It takes 4 to 6 seconds for the website to become functional.
This is the code I have to implement.
<div id="[reservation-company-name]-booknow">
<script type="text/javascript" src="//www.[reservation-company-name].com/WID/Widget/Cors"></script>
<script>bookNow({companyID: '[numbers]',target: '#[reservation-company-name]-booknow',language: 'NL'});</script>
</div>
The reservation widget is hidden on the homepage, but that still means the scripts will load while the webpage.
I knew I had to dynamically load the scripts after the page is fully loaded.
$(window).load(function() {
$("#[reservation-company-name]-booknow").append("<script type='text/javascript' src='//www.[reservation-company-name].com/WID/Widget/Cors'></script><script>bookNow({companyID: '[numbers]',target: '#[reservation-company-name]-booknow',language: 'NL'});</script>
});
Problem is however, that the second script with the bookNow function fires while the first script is still being loaded. This results in an error and the widget won't load properly.
The widget will load when I set a timeout on running the second script, but with different connection speeds, it's impossible to set the right timing on the timeout.
I've searched here on Stackoverflow on how to wait for a dynamically loaded script to fully load before executing a function. Most stuff I found wasn't about dynamically loaded scripts or was about asyncing and deferring, which didn't work for me.
What to do?
$(window).load()is deprecated. Use$(window).on('load').