طرح پیشنهادی برای بارگذاری پویای ماژولهای JS
نویسنده: بهنام محمدی
تاریخ: ۱۳۹۵/۱۰/۲۱ ۲۳:۵۵
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
import someModule from './dir/someModule.js';
import('./dir/someModule.js')
.then(someModule => someModule.foo()); button.addEventListener('click', event => {
import('./dialogBox.js')
.then(dialogBox => {
dialogBox.open();
})
.catch(error => {
/* Error handling */
})
}); import('./myModule.js')
.then(({export1, export2}) => {
export1.run();
export2.fire();
}); Promise.all([
import('./module1.js'),
import('./module2.js'),
import('./module3.js'),
])
.then(([module1, module2, module3]) => {
// code
}); async function main() {
const myModule = await import('./myModule.js');
myModule.getInfo();
const {export1, export2} = await import('./myModule.js');
export1.run();
export2.fire()
}
main(); البته آقای Jake Archibald کد جالبی را برای این قابلیت پیشنهاد دادهاست که ترکیبی از import استاتیک ES6 میباشد:
function importModule (url) {
return new Promise((resolve, reject) => {
const script = document.createElement("script");
const tempGlobal = "__tempModuleLoadingVariable" + Math.random().toString(32).substring(2);
script.type = "module";
script.textContent = `import * as m from "${url}"; window.${tempGlobal} = m;`;
script.onload = () => {
resolve(window[tempGlobal]);
delete window[tempGlobal];
script.remove();
};
script.onerror = () => {
reject(new Error("Failed to load module script with URL " + url));
delete window[tempGlobal];
script.remove();
};
document.documentElement.appendChild(script);
});
}