JavaScript || Resources.js – JavaScript & CSS Parallel File Loader To Dynamically Import & Load Files To Page Document Using Vanilla JavaScript
The following is a module that handles loading JavaScript and CSS files into a document in parallel, as fast as the browser will allow. This module also allows to ensure proper execution order if you have dependencies between files.
Contents
1. Load Files One By One
2. Load Multiple Files In Parallel
3. Load Multiple Files In Parallel With Dependencies
4. Load A JavaScript Function From Another JS File
5. Resources.js Namespace
6. More Examples
Syntax is very straightforward. The following demonstrates loading single files one by one:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
// Load JavaScript and CSS files one by one. <script> (async () => { // Load files one by one await Resources.load('/file1.js'); await Resources.load('/file2.js'); await Resources.load('/file3.css'); await Resources.load('/file4.css'); await Resources.load('https://code.jquery.com/jquery-3.5.1.js'); await Resources.load('https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js'); })(); </script> |
The ‘Resources.load‘ function returns an object that contains information about the load status. It can let you know if a file was loaded successfully or not.
To get the load status in order to determine if the file was loaded correctly, it can be done like so:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
// Load JavaScript and CSS files one by one and verify. <script> (async () => { // Load files one by one console.log(await Resources.load('/file1.js')); console.log(await Resources.load('/file2.js')); console.log(await Resources.load('/file3.css')); console.log(await Resources.load('/file4.css')); console.log(await Resources.load('https://code.jquery.com/jquery-3.5.1.js')); console.log(await Resources.load('https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js')); })(); </script> // expected output: /* [ { url: "/file1.js", loaded: false, notes: "*** /file1.js failed to load ***" } ] [ { url: "/file2.js", loaded: false, notes: "*** /file2.js failed to load ***" } ] [ { url: "/file3.css", loaded: false, notes: "*** /file3.css failed to load ***" } ] [ { url: "/file4.css", loaded: false, notes: "*** /file4.css failed to load ***" } ] [ { url: "https://code.jquery.com/jquery-3.5.1.js", loaded: true, notes: "https://code.jquery.com/jquery-3.5.1.js loaded" } ] [ { url: "https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js", loaded: true, notes: "https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js loaded" } ] */ |
In the example above, the load results can let you know which files were loaded into the document, and the reason for failure.
2. Load Multiple Files In Parallel
In the examples above, files were added sequentially, one by one.
Ideally, you would want to load all of your files at once in parallel. This makes it so you are able to add multiple files as fast as the browser will allow. Parallel loading also allows you to set if there are any file dependencies.
Using the files from the examples above, this can be done like so.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
// Load JavaScript and CSS files in parallel. <script> (async () => { // Load files in parallel let loadResult = await Resources.load({ files: [ { url: '/file1.js', type: 'js', wait: false }, { url: '/file2.js', type: 'js', wait: false }, { url: '/file3.css', type: 'css', wait: false }, { url: '/file4.css', type: 'css', wait: false }, { url: 'https://code.jquery.com/jquery-3.5.1.js', type: 'js', wait: false }, { url: 'https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js', type: 'js', wait: false }, ], logResults: true, rejectOnError: false, timeout: null }); console.log(loadResult); })(); </script> // possile output: /* [ { "url": "/file3.css", "loaded": false, "notes": "*** /file3.css failed to load ***" }, { "url": "/file4.css", "loaded": false, "notes": "*** /file4.css failed to load ***" }, { "url": "/file1.js", "loaded": false, "notes": "*** /file1.js failed to load ***" }, { "url": "/file2.js", "loaded": false, "notes": "*** /file2.js failed to load ***" }, { "url": "https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js", "loaded": true, "notes": "https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js loaded" }, { "url": "https://code.jquery.com/jquery-3.5.1.js", "loaded": true, "notes": "https://code.jquery.com/jquery-3.5.1.js loaded" } ] */ |
For parallel loading, the parameter supplied to the ‘Resources.load‘ function is an object that is made up of the following properties.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
{ • files: An object array of 'File Info' of files to load (See below). • logResults: Optional. Boolean that indicates if the load status should be displayed to console.log(). Default is false. • rejectOnError: Optional. Boolean that indicates if the load operation should reject if a loading error occurs for any file in the group. Default is false. • timeout: Optional. Integer that indicates how long to wait (in milliseconds) for the file group to load before timeout occurs. Default is null. // ** 'File Info': This is made up of the following properties { • url: The source url to load. • type: Optional. String indicating the file type to load. Options are 'css' or 'js'. Default type is determined by the file extension if not supplied. • wait: Optional. Boolean that indicates if this file should be completely loaded before loading subsequent files in the group. • If set to true, other urls are not loaded until this one finishes loading. After loading this file, other files continue loading in parallel • If set to false, no wait occurs and files load in parallel. This makes it so dependent files dont get loaded until the required files are loaded first. Files with this property set to true are loaded before any other file in the group. Default is false. } } |
3. Load Multiple Files In Parallel With Dependencies
The ‘wait‘ property is a great way to manage file dependencies. When the ‘wait‘ property is set to true, that indicates that the file should be completely loaded before loading subsequent files in the group.
This makes it so loading files in parallel does not cause files to be loaded before its dependent files.
The following examples demonstrates the ‘wait‘ functionality when loading files in parallel.
The example below demonstrates what happens when ‘wait‘ is not used. Load order behavior is undefined because files are loaded as they become available. This could cause an issue if the second file depends on the first file, but loads before it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
// Load JavaScript and CSS files in parallel. // Load order behavior is undefined because files // are loaded as they become available <script> (async () => { // Load files in parallel let loadResult = await Resources.load({ files: [ { url: 'https://code.jquery.com/jquery-3.5.1.js', type: 'js', wait: false }, { url: 'https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js', type: 'js', wait: false }, ], logResults: true, rejectOnError: false, timeout: null }); console.log(loadResult); })(); </script> /* // possible output: [ { "url": "https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js", "loaded": true, "notes": "https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js loaded" }, { "url": "https://code.jquery.com/jquery-3.5.1.js", "loaded": true, "notes": "https://code.jquery.com/jquery-3.5.1.js loaded" } ] */ |
In the example below, the ‘wait‘ property is set to true for the first file, ensuring that it will always be loaded before any subsequent files.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
// Load JavaScript and CSS files in parallel. // Load behavior is managed using wait <script> (async () => { // Load files in parallel let loadResult = await Resources.load({ files: [ { url: 'https://code.jquery.com/jquery-3.5.1.js', type: 'js', wait: true }, { url: 'https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js', type: 'js', wait: false }, ], logResults: true, rejectOnError: false, timeout: null }); console.log(loadResult); })(); </script> /* // expected output: [ { "url": "https://code.jquery.com/jquery-3.5.1.js", "loaded": true, "notes": "https://code.jquery.com/jquery-3.5.1.js loaded" }, { "url": "https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js", "loaded": true, "notes": "https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js loaded" } ] */ |
4. Load A JavaScript Function From Another JS File
‘Resources.load‘ could be used to call a JavaScript function in another js file. The example below demonstrates this.
In the following example, main.html is the ‘driver’ file. It loads ‘fullName.js‘ to get the functions located in that file. ‘fullName.js‘ then uses ‘Resources.load‘ to load the files ‘display.js‘, ‘log.js‘ and ‘date.js‘, and calls the functions from those files to display information.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
<!-- // main.html // This file loads functions from fullName.js --> <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>My Programming Notes Resources.js Demo</title> <style> .main { text-align:center; margin-left:auto; margin-right:auto; } </style> <!-- Include Resources.js --> <script type="text/javascript" src="./Resources.js"></script> </head> <body> <div class="main"> My Programming Notes Resources.js Demo </div> <script> (async () => { // Load fullname.js to get the 'fullname' functions await Resources.load({ files: [ './fullName.js' ], logResults: true }); // Fucntions from fullname.js let fullName = getFullName('Kenneth', 'P'); // This calls a function in display.js via fullname.js with no return value await displayFullName(fullName).catch((error) => { // Log if any errors occur console.log('Failed:', error); }); // This calls a function in log.js via fullname.js with no return value await logFullName(fullName).catch((error) => { // Log if any errors occur console.log('Failed:', error); }); // This calls a function in date.js via fullname.js that rerturns a value try { alert(await getFullNameWithDate(fullName)); } catch (error) { // Log if any errors occur console.log('Failed:', error); } })(); </script> </body> </html> <!-- // expected output: *** Resources.js Load Status *** ./fullName.js loaded *** Resources.js Load Status *** ./display.js loaded ./log.js loaded ./date.js loaded [ALERT: Kenneth P] Kenneth P [ALERT: Name: Kenneth P Date: 7/7/2020, 12:09:44 PM] --> |
Below is fullName.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
// fullName.js // Load the 'display', 'log' and 'getDateString' functions // from the files below. let dependencies = Resources.load({ files: [ './display.js', './log.js', './date.js' ], logResults: true }); let getFullName = (firstName, lastName) => { return `${firstName} ${lastName}`; } // Uses the 'display' function from display.js let displayFullName = (fullName) => { return new Promise(async (resolve, reject) => { try { // Make sure the dependencies have loaded. // The load status is logged to the console. let status = await dependencies; //console.log(status); display(fullName); resolve(); } catch (error) { // Log if any errors occur //console.log('Failed:', error); reject(error); } }); } // Uses the 'log' function from log.js let logFullName = (fullName) => { return new Promise(async (resolve, reject) => { try { // Make sure the dependencies have loaded. // The load status is logged to the console. let status = await dependencies; //console.log(status); log(fullName); resolve(); } catch (error) { // Log if any errors occur //console.log('Failed:', error); reject(error); } }); } // Uses the 'getDateString' function from date.js that returns a value let getFullNameWithDate = (fullName) => { return new Promise(async (resolve, reject) => { try { // Make sure the dependencies have loaded. // The load status is logged to the console. let status = await dependencies; //console.log(status); let date = getDateString(new Date()); resolve(`Name: ${fullName}\nDate: ${date}`); } catch (error) { // Log if any errors occur //console.log('Failed:', error); reject(error); } }); } |
Below is display.js
1 2 3 4 5 |
// display.js let display = (data) => { alert(data); } |
Below is log.js
1 2 3 4 5 |
// log.js let log = (data) => { console.log(data); } |
Below is date.js
1 2 3 4 5 |
// date.js let getDateString = (date) => { return date.toLocaleString(); } |
5. Resources.js Namespace
The following is the Resources.js Namespace. Include this in your project to start using!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 |
// ============================================================================ // Author: Kenneth Perkins // Date: Jul 7, 2020 // Taken From: http://programmingnotes.org/ // File: Resources.js // Description: Javascript that loads Javascript and CSS files // into a document in parallel, as fast as the browser will allow. // This allows to ensure proper execution order if you have dependencies // between files. // Example: // // Load JavaScript and CSS files and wait for them to load // const dependencies = await Resources.load({ // files: [ // { url: '/file1.js', type: 'js', wait: false }, // { url: '/file2.js', type: 'js', wait: false }, // { url: '/file3.css', type: 'css', wait: false }, // { url: '/file4.css', type: 'css', wait: false }, // { url: 'https://code.jquery.com/jquery-3.5.1.js', type: 'js', wait: true }, // { url: 'https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js', type: 'js', wait: false }, // ], // logResults: true, // rejectOnError: false, // timeout: null // }); // ============================================================================ /** * NAMESPACE: Resources * USE: Handles loading Javascript and CSS files in parallel. */ var Resources = Resources || {}; (function(namespace) { 'use strict'; // -- Public data -- // Property to hold public variables and functions let exposed = namespace; /** * FUNCTION: load * USE: Loads Css and/or Javascript files into a document in * parallel, depending on the options * @param options: An object of file loading options. * Its made up of the following properties: * { * files: An object array of File info of files to load (See below). * logResults: Optional. Boolean that indicates if the load * status should be displayed to console.log(). * Default is false. * rejectOnError: Optional. Boolean that indicates if the load * operation should reject if a loading error occurs for * any file in the group. * Default is false. * timeout: Optional. Integer that indicates how long to wait * (in milliseconds) for the file group to load before timeout occurs. * Default is null. * } * * ** File info: This is made up of the following properties * { * url: The source url to load. * type: Optional. String indicating the file type to load. * Options are 'css' or 'js'. * Default type is determined by the file extension. * wait: Optional. Boolean that indicates if this file should be * completely loaded before loading subsequent files in the group. * If set to true, other urls are not loaded until this one * finishes loading. After loading this file, other files * continue loading in parallel. * If set to false, no wait occurs and files load in parallel. * This makes it so dependent files dont get loaded until the * required files are loaded first. * Files with this property set to true are loaded before * any other file in the group. * Default is false. * } * @return: A promise that completes when all resources are loaded, which * contains an array of each files loading status. */ exposed.load = (options) => { return new Promise(async (resolve, reject) => { try { // Load files and wait for the results options = verifyOptions(options); let results = await loadFiles(options); if (options.logResults) { console.log('*** Resources.js Load Status ***') let notes = results.map((x) => x.notes); console.log(notes.join('\n')); } resolve(results); } catch (e) { reject(e); } }); } /** * FUNCTION: loadJs * USE: Loads a Javascript file into a document * @param url: The javascript url to load. * @return: A promise that completes when the url is loaded. */ exposed.loadJs = (url) => { return new Promise((resolve, reject) => { // Load file and attach it to the document let status = createFileStatus(url); try { if (fileExists(url)) { status.loaded = true; status.notes = `${url} already loaded`; resolve(status); return; } let script = document.createElement("script"); script.src = url; script.type = "text/javascript" script.id = getId(url); script.onload = script.onreadystatechange = function() { if ((!this.readyState || this.readyState == "loaded" || this.readyState == "complete") ) { status.loaded = true; status.notes = `${url} loaded`; resolve(status); } } script.onerror = () => { removeFile(url); status.notes = `*** ${url} failed to load ***`; reject(status); } document.getElementsByTagName("head")[0].appendChild(script); addFile(url); } catch (e) { let message = e.message ? e.message : e; status.notes = `*** ${url} failed to load. Reason: ${message} ***`; reject(status); } }); } /** * FUNCTION: loadCss * USE: Loads a Css file into a document * @param url: The css url to load. * @return: A promise that completes when the url is loaded. */ exposed.loadCss = (url) => { return new Promise((resolve, reject) => { // Load file and attach it to the document let status = createFileStatus(url); try { if (fileExists(url)) { status.loaded = true; status.notes = `${url} already loaded`; resolve(status); return; } let link = document.createElement('link'); link.type = 'text/css'; link.rel = 'stylesheet'; link.onload = () => { status.loaded = true; status.notes = `${url} loaded`; resolve(status); } link.onerror = () => { removeFile(url); status.notes = `*** ${url} failed to load ***`; reject(status); } link.href = url; link.id = getId(url); document.getElementsByTagName("head")[0].appendChild(link); addFile(url); } catch (e) { let message = e.message ? e.message : e; status.notes = `*** ${url} failed to load. Reason: ${message} ***`; reject(status); } }); } /** * FUNCTION: getFilename * USE: Returns the filename of a url * @param url: The url. * @return: The filename of a url. */ exposed.getFilename = (url) => { let filename = ''; if (url && url.length > 0) { filename = url.split('\\').pop().split('/').pop(); // Remove any querystring if (filename.indexOf('?') > -1) { filename = filename.substr(0, filename.indexOf('?')); } } return filename; } /** * FUNCTION: getExtension * USE: Returns the file extension of the filename of a url * @param url: The url. * @return: The file extension of a url. */ exposed.getExtension = (url) => { let filename = exposed.getFilename(url); let ext = filename.split('.').pop(); return (ext === filename) ? '' : ext; } // -- Private data -- let loadFiles = (options) => { return new Promise(async (resolve, reject) => { try { if (!options.files) { throw new Error('There are no files specified to load.'); } let files = verifyArray(options.files); // Order the files putting the critical ones first prioritizeFiles(files); // Load files to the document let results = []; let promises = []; for (let file of files) { file = verifyFile(file); let promise = getCallback(file).call(this, file.url); if (file.wait) { let value = await resolveByCompletion([promise], options.rejectOnError, options.timeout); results.push(value[0]); } else { promises.push(promise); } } // Get the results let completed = await resolveByCompletion(promises, options.rejectOnError, options.timeout); results = [...results, ...completed]; resolve(results); } catch (e) { let message = e.message ? e.message : e.notes ? e.notes : e; reject(new Error(`Unable to load resources. Reason: ${message}`)); } }); } let prioritizeFiles = (files) => { files.sort((x, y) => { let conditionX = x.wait || false; let conditionY = y.wait || false; return conditionY - conditionX; }); return files; } let getCallback = (file) => { let types = { css: exposed.loadCss, js: exposed.loadJs } let callback = types[file.type.toLocaleLowerCase()]; if (!callback) { throw new Error(`Unknown file type/file extension (${file.type}) for the following url: ${file.url}`); } return callback; } let getId = (str) => { return `${str}_added_resource` } let fileExists = (url) => { return loadedResources.has(url) || (document.querySelector(`script[src='${url}']`) != null); } let addFile = (url) => { loadedResources.set(url, true); } let removeFile = (url) => { return loadedResources.delete(url); } let createFileStatus = (url) => { let status = { url: url, loaded: false, notes: '', } return status; } let verifyOptions = (options) => { if (!options) { throw new Error('There are no options specified'); } if (typeof options !== 'object' || Array.isArray(options)) { let files = options; options = {}; options.files = files; } options.rejectOnError = options.rejectOnError || false; options.timeout = options.timeout|| null; return options; } let verifyArray = (arry) => { if (!arry) { arry = []; } if (!Array.isArray(arry)) { arry = [arry]; } return arry; } let verifyFile = (file) => { if (typeof file !== 'object') { let url = file; file = {}; file.url = url; } file.url = file.url || ''; file.wait = file.wait || false; file.type = file.type || exposed.getExtension(file.url); return file } /** * FUNCTION: resolveByCompletion * USE: Returns a promise that will resolve when all of the input's * promises have resolved, in order of completion. * @param promises: An array of promises. * @param rejectOnError: Optional. Boolean that indicates if the operation * should reject if any of the input promises reject or throw an error. * If set to true, the operation is rejected if any of the input * promises reject or throw an error. * If set to false, the promises rejected value is added to the result list. * @param timeout: Optional. Integer that indicates how long to wait * (in milliseconds) for the promise group to complete. * @return: A promise that will contain the input promises results on completion. */ let resolveByCompletion = (promises, rejectOnError = true, timeout = null) => { return new Promise(async (resolve, reject) => { try { let results = [] let promiseMap = new Map(); Array.prototype.forEach.call(promises, (promise, index) => { let promiseResult = { index: index, value: null, error: null }; let mapValue = null; if (promise instanceof Promise) { mapValue = promise .then(value => {promiseResult.value = value; return promiseResult}) .catch(error => {promiseResult.error = error; return promiseResult}) } else { mapValue = promiseResult; promiseResult.value = promise; } promiseMap.set(index, mapValue); }); let start = Date.now(); let isTimedOut = () => { let result = false; if (timeout) { let elapsed = (Date.now() - start); result = elapsed >= timeout; } return result; } while (promiseMap.size > 0) { let promiseResult = await Promise.race(promiseMap.values()); if (!promiseMap.delete(promiseResult.index)) { throw new Error('Error occurred processing values'); } if (promiseResult.error) { if (rejectOnError) { reject(promiseResult.error); return; } results.push(promiseResult.error); } else { results.push(promiseResult.value); } if (isTimedOut()) { throw new Error(`Timeout of ${timeout}ms expired`); } } resolve(results); } catch (e) { reject(e); } }); } let loadedResources = new Map(); (function (factory) { if (typeof define === 'function' && define.amd) { define([], factory); } else if (typeof exports === 'object') { module.exports = factory(); } }(function() { return namespace; })); }(Resources)); // http://programmingnotes.org/ |
6. More Examples
Below are more examples demonstrating the use of ‘Resources.load‘. Don’t forget to include the module when running the examples!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 |
<!-- // ============================================================================ // Author: Kenneth Perkins // Date: Jul 7, 2020 // Taken From: http://programmingnotes.org/ // File: resourcesDemo.html // Description: Demonstrates the use of Resources.js // ============================================================================ --> <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>My Programming Notes Resources.js Demo</title> <style> .main { text-align:center; margin-left:auto; margin-right:auto; } .output { text-align: left; } pre {outline: 1px solid #ccc; padding: 5px; margin: 5px; } .string { color: green; } .number { color: darkorange; } .boolean { color: blue; } .null { color: magenta; } .key { color: red; } </style> <!-- // Include module --> <script type="text/javascript" src="./Resources.js"></script> </head> <body> <div class="main"> My Programming Notes Resources.js Demo <pre><code><div class="output"></div></code></pre> </div> <script> (async () => { // Load files in parallel with undefined loading order let loadResult = await Resources.load({ files: [ { url: 'https://code.jquery.com/jquery-3.5.1.js', type: 'js' , wait: false }, { url: 'https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js', type: 'js' , wait: false }, ], logResults: true, rejectOnError: false, timeout: null }); console.log(loadResult); print('Resources.load Status Result with undefined loading order', loadResult, 4); })(); </script> <script> (async () => { return; // Load files in parallel with defined loading order let loadResult = await Resources.load({ files: [ { url: 'https://code.jquery.com/jquery-3.5.1.js', type: 'js' , wait: true }, { url: 'https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js', type: 'js' , wait: false }, ], logResults: true, rejectOnError: false, timeout: null }); console.log(loadResult); print('Resources.load Status Result with defined loading order', loadResult, 4); })(); </script> <script> (async () => { return; // Load fullname.js to get the 'fullname' functions await Resources.load({ files: ['./fullName.js'], logResults: true, }); let fullName = getFullName('Kenneth', 'P'); displayFullName(fullName); logFullName(fullName); })(); </script> <script> (async () => { return; // Load files one by one console.log(await Resources.load('/file1.js')); console.log(await Resources.load('/file2.js')); console.log(await Resources.load('/file3.css')); console.log(await Resources.load('/file4.css')); console.log(await Resources.load('https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js')); })(); </script> <script> function print(desc, obj, indent = 0) { let text = (desc.length > 0 ? '<br />' : '') + desc + (desc.length > 0 ? '<br />' : ''); let objText = obj || ''; if (obj && typeof obj != 'string') { objText = syntaxHighlight(JSON.stringify(obj, null, indent)); } text += objText; let pageText = document.querySelector('.output').innerHTML; pageText += (pageText.length > 0 ? '<br />' : '') + text; document.querySelector('.output').innerHTML = pageText; } function syntaxHighlight(json) { if (typeof json != 'string') { json = JSON.stringify(json, undefined, 2); } json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>'); return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) { let cls = 'number'; if (/^"/.test(match)) { if (/:$/.test(match)) { cls = 'key'; } else { cls = 'string'; } } else if (/true|false/.test(match)) { cls = 'boolean'; } else if (/null/.test(match)) { cls = 'null'; } return '<span class="' + cls + '">' + match + '</span>'; }); } </script> </body> </html><!-- // http://programmingnotes.org/ --> |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Leave a Reply