Sorry not a native English speaker.
I have a async data which get from other module to import.
when I import, DOMContentLoaded and load event won’t’ be triggered. And when I comment out import, it work
// main.js
<head>
<script type="module">
import test from "/js/test.js";
console.log(test); // has data
// can only work when comment out import
window.addEventListener("DOMContentLoaded", () => {
console.log("DOMContentLoaded");
});
// can only work when comment out import
window.addEventListener("load", () => {
console.log("load");
});
// work no matter import module or not
$(document).ready(() => {
console.log("ready");
});
</script>
</head>
// test.js
let test = await f();
async function f() {
const r = await fetch("url", {
method: "post",
body: JSON.stringify({
"key": "value"
}),
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
}
})
.then((res) => res.json())
.then((result) => {
return result;
})
return r;
}
console.log(test); // has data
export default test
And there is another example, load event is work!
// main.js (still put in head)
import { Data } from '/js/global/Data';
console.log(Data); // has data
// not work
window.addEventListener("DOMContentLoaded", () => {
console.log("DOMContentLoaded");
});
// not work
window.addEventListener("DOMContentLoaded", async () => {
console.log("DOMContentLoaded");
});
// it work!
window.addEventListener("load", () => {
console.log("load");
});
// it work!
window.addEventListener("load", async () => {
console.log("load");
});
// js/global/Data
import { storage_setItem, storage_getItem, storage_remove } from '/js/module/localStorage';
let Data;
storage_remove("Data");
Data = await get() ?? await save(getDefault());
Data = Data.datas;
console.log(Data);
async function get() {
return await storage_getItem("Data");
}
async function save(data) {
await storage_setItem("Data", data);
return await get();
}
function getDefault() {
return {
datas: {}
}
}
export {
Data,
get,
save
}
// js/module/localStorage
import { Preferences } from '@capacitor/preferences';
async function storage_setItem(key, value) {
await Preferences.set({
key: key,
value: typeof value == "object" ? JSON.stringify(value) : value
});
}
async function storage_getItem(key) {
const ret = await Preferences.get({ key: key });
return typeof JSON.parse(ret.value) == "object" ? JSON.parse(ret.value) : ret.value;
}
async function storage_remove(key) {
await Preferences.remove({ key: key })
}
export {
storage_setItem,
storage_getItem,
storage_remove
}