Skip to content

Instantly share code, notes, and snippets.

View gpDA's full-sized avatar
🏠
Working from home

GP LEE gpDA

🏠
Working from home
View GitHub Profile
function loadScript(src) {
// creates a <script> tag and append it to the page
// this causes the script with given src to start loading and run when complete
let script = document.createElement('script');
script.src = src;
document.head.append(script);
}
// load and execute the script at the given path
loadScript('/my/script.js');
loadScript('/my/script.js'); // the script has "function newFunction() {…}"
// the code below loadScript
// doesn't wait for the script loading to finish
// ...
newFunction(); // no such function!
// define function loadScript
function loadScript(src, callback) {
let script = document.createElement('script');
script.src = src;
script.onload = () => callback(script);
document.head.append(script);
}
loadScript('/my/script.js', function(script) {
loadScript('/my/script2.js', function(script) {
loadScript('/my/script3.js', function(script) {
// ...continue after all scripts are loaded
});
})
// DEFINE function in Promise way
function loadScript(src) {
return new Promise(function(resolve, reject) {
let script = document.createElement('script');
script.src = src;
script.onload = () => resolve(script);
script.onerror = () => reject(new Error(`Script load error for ${src}`));
document.head.append(script);
function printString(string, callback) {
setTimeout(
() => {
console.log(string)
callback()
},
1 * 1000 // 1s
)
}
function printAll() {
printString("A", () => {
printString("B", () => {
printString("C", () => {})
})
})
}
printAll()
function printString(string) {
return new Promise((resolve, reject) => {
setTimeout(
() => {
console.log(string)
resolve()
},
1 * 1000
)
})
function printAll() {
printString("A")
.then(() => {
return printString("B")
})
.then(() => {
return printString("C")
})
}