I dont understand how this works | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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

15th Apr 2021, 1:38 AM
sid
sid - avatar
2 Answers
+ 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 });
15th Apr 2021, 2:16 AM
Josh Greig
Josh Greig - avatar
+ 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).
15th Apr 2021, 9:48 AM
CamelBeatsSnake
CamelBeatsSnake - avatar