返回 reveal.js
loader.ts
根目录 / js / utils / loader.ts
1 /**
2 * Loads a JavaScript file from the given URL and executes it.
3 *
4 * @param {string} url Address of the .js file to load
5 * @param {function} callback Method to invoke when the script
6 * has loaded and executed
7 */
8 export const loadScript = (url: string, callback?: (error?: Error) => void) => {
9 const script = document.createElement('script');
10 script.type = 'text/javascript';
11 script.async = false;
12 script.defer = false;
13 script.src = url;
14
15 if (typeof callback === 'function') {
16 // Success callback
17 script.onload = (event: Event) => {
18 if (event.type === 'load') {
19 // Kill event listeners
20 script.onload = script.onerror = null;
21
22 callback();
23 }
24 };
25
26 // Error callback
27 script.onerror = (err: Event | string) => {
28 // Kill event listeners
29 script.onload = script.onerror = null;
30
31 callback(new Error('Failed loading script: ' + script.src + '\n' + err));
32 };
33 }
34
35 // Append the script at the end of <head>
36 const head = document.querySelector('head');
37 if (head) {
38 head.insertBefore(script, head.lastChild);
39 }
40 };
41
41 lines TYPESCRIPT