+ 3
I dont understand how this works
How the 4th line works with callback function. Why we give script as a parameter to the callback function. https://code.sololearn.com/WVCo8uwFeEFN/?ref=app
2 Respostas
+ 4
The code looks like just an educational example so the reason could just be to show you that you can and help you see how to pass parameters to your callback function.
The script src attribute is the same as what was passed to the loadScript function so the caller already knows what the src is going to be. The caller might as well be written like this and ignore any parameters:
var src = 'https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.2.0/lodash.js';
loadScript(src, () => {
alert(`Cool, the script ${src} is loaded`);
alert( _ );
// function declared in the loaded script
});
+ 1
The intention of the code is to load the lodash code as a script. After it has loaded, show a message to indicate that it has (line 6) and show the global variable you get from the lodash script (line 7).
Line 4 shows how to handle an asynchronous event. It's asynchronous because the load event takes some time, and while that's happening, you can execute other code. Put a log or alert on line 5 to see this clearly.
We only want to run the callback function once the script has loaded. So after it loads, we fire the callback with the script as the argument to the callback. As Josh Greig said, the src itself could easily be passed to the callback because the callback only uses the script to access the source in the alert (line 6).