I'm creating a plugin system for a library. I'm getting the function from another file with ajax, wrapping and returning only the function with the Function constructor and then add the function to the window object and I'm doing this in a loop and at last when i'm checking the window object, it's empty. why?
Here's the code
x.html (Main File)
<html>
<head>
<script src="//cdn.jsdelivr.net/npm/eruda"></script><script>eruda.init();</script>
<script>
window.addEventListener('error', function(e) {
console.error(e, e.message, e.filename, e.lineno, e.colno, e.error);
});
if (typeof window.example !== 'object') {
window.example = {
plugins: {}
};
}
</script>
</head>
<body>
Text
<script type="module">
import { loadPlugin } from "./y.js";
await loadPlugin(['bold','italic']);
console.log(window.example.plugins)
console.log(window.example.plugins.italic)
</script>
</body>
</html>
y.js (Importer)
export async function loadPlugin(plugins, namespace) {
for (var i = 0; i < plugins.length; i++) {
if (typeof window.example.plugins[plugins[i]] === 'undefined') {
fetch(`z.js`)
.then((response) => response.text())
.then(function(code) {
if (code.trim() !== '') {
try {
code += 'return theme;'
window.example.plugins[plugins[i]] = (new Function(code))();
} catch (err) {
console.log(err);
}
}
});
}
if (i === (plugins.length - 1)) {
return new Promise(function(resolve) {
resolve(window.example.plugins);
});
}
}
}
z.html (The file to import function from)
function theme() {
console.log('Hooray!');
}
I hope you all understood the problem yet, please help.
Thanks ,