This commit is contained in:
Ilya Kantor 2017-07-01 10:44:36 +03:00
parent eca29f5238
commit 7895f3d3ae

View file

@ -29,7 +29,8 @@ The call initiates the script loading, then the execution continues. While the s
```js
loadScript('/my/script.js');
// the code below doesn't wait for the script loading to finish
// the code below loadScript doesn't wait for the script loading to finish
// ...
```
Now let's say we want to use the new script when it loads. It probably declares new functions, so we'd like to run them.
@ -44,7 +45,7 @@ newFunction(); // no such function!
*/!*
```
Naturally, the browser probably didn't have time to load the script. As of now, `loadScript` function doesn't provide a way to track the load completion. The script loads and eventually runs, that's all. But we'd like to know when happens, to use new functions and variables from that script.
Naturally, the browser probably didn't have time to load the script. So the immediate call to the new function fails. As of now, `loadScript` function doesn't provide a way to track the load completion. The script loads and eventually runs, that's all. But we'd like to know when happens, to use new functions and variables from that script.
Let's add a `callback` function as a second argument to `loadScript` that should execute when the script loads:
@ -150,7 +151,7 @@ function loadScript(src, callback) {
*!*
script.onload = () => callback(null, script);
script.onerror = () => callback(new Error(`Script load error ` + src));
script.onerror = () => callback(new Error(`Script load error for ${src}`));
*/!*
document.head.append(script);