I have seen the following code in a JavaScript tutorial:
function loadScript(src) {
// creates a <script> tag and append it to the page
// this causes the script with given src to start loading and run when complete
let script = document.createElement('script');
script.src = src;
document.head.append(script);
}
loadScript('/my/script.js');
// the code below loadScript
// doesn't wait for the script loading to finish
// ...
The comment says:
The script is executed “asynchronously”, as it starts loading now, but runs later, when the function has already finished.
- Why is this script executed asynchronously? What inside or outside the function
loadScript
makes the code execute asynchronously?
The following code uses a corrected version of the function defined above, that takes into account the synchronization with dependent code:
function loadScript(src, callback) {
let script = document.createElement('script');
script.src = src;
script.onload = () => callback(script);
document.head.append(script);
}
loadScript('https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.2.0/lodash.js', script => {
alert(`Cool, the script ${script.src} is loaded`);
alert( _ ); // function declared in the loaded script
});
What does the underscore in the alert call mean?
Why does it alert the first function in the loaded script?
Is this the only way to do the synchronization? I would not call it a clean design because it ties two separate functions just because of how they may be called.