🪄 尝试优化异步加载的配置执行,使其生效

This commit is contained in:
hi2hi 2025-11-10 17:55:13 +08:00
parent 640fd787a2
commit ec3b5cb5ea

View File

@ -54,6 +54,7 @@ const store = useStore();
const footerSlogan = computed(() => decodeURIComponent(config.nazhua?.footerSlogan || '')); const footerSlogan = computed(() => decodeURIComponent(config.nazhua?.footerSlogan || ''));
const dynamicContentRef = ref(); const dynamicContentRef = ref();
const executedScripts = ref(new Set()); //
const dynamicContent = computed(() => { const dynamicContent = computed(() => {
if (store.state.setting?.config?.custom_code) { if (store.state.setting?.config?.custom_code) {
@ -69,24 +70,69 @@ const dynamicContent = computed(() => {
const executeScripts = () => { const executeScripts = () => {
nextTick(() => { nextTick(() => {
if (!dynamicContentRef.value) return; if (!dynamicContentRef.value) return;
const scripts = dynamicContentRef.value.querySelectorAll('script'); const scripts = dynamicContentRef.value.querySelectorAll('script');
scripts.forEach((script) => { scripts.forEach((script) => {
const newScript = document.createElement('script'); try {
newScript.type = 'text/javascript'; //
if (script.src) { const scriptIdentifier = script.src || script.textContent || '';
newScript.src = script.src; // src if (!scriptIdentifier || executedScripts.value.has(scriptIdentifier)) {
} else { return;
newScript.textContent = script.textContent; // }
const newScript = document.createElement('script');
newScript.type = script.type || 'text/javascript';
//
if (script.async !== undefined) newScript.async = script.async;
if (script.defer !== undefined) newScript.defer = script.defer;
if (script.crossOrigin) newScript.crossOrigin = script.crossOrigin;
if (script.integrity) newScript.integrity = script.integrity;
if (script.noModule !== undefined) newScript.noModule = script.noModule;
if (script.referrerPolicy) newScript.referrerPolicy = script.referrerPolicy;
if (script.src) {
//
newScript.src = script.src;
newScript.onload = () => {
executedScripts.value.add(scriptIdentifier);
};
newScript.onerror = (error) => {
console.error('Failed to load external script:', script.src, error);
};
document.body.appendChild(newScript);
} else {
//
newScript.textContent = script.textContent;
document.body.appendChild(newScript);
executedScripts.value.add(scriptIdentifier);
//
document.body.removeChild(newScript);
}
} catch (error) {
console.error('Error executing dynamic script:', error);
} }
document.body.appendChild(newScript);
document.body.removeChild(newScript); //
}); });
}); });
}; };
watch(dynamicContent, () => { //
if (dynamicContent.value) { const cleanupScripts = () => {
executeScripts(); executedScripts.value.clear();
};
watch(dynamicContent, (newVal, oldVal) => {
//
if (newVal !== oldVal) {
cleanupScripts();
}
if (newVal) {
// DOM
nextTick(() => {
executeScripts();
});
} }
}); });