javascript - 加载新网页而不重新加载加载脚本错误
问题描述
我正在尝试让 Web 应用程序加载新页面而不在浏览器中重新加载。由于脚本未加载,某些页面工作正常,而其他页面则引发错误。以下代码是加载新页面的代码
function loadPage(target, savePushState){
$(".page-content").fadeOut(function(){
$('body').load(target, function(data) {
$(".page-content").fadeIn(function(){
var newTitle = $(data).filter('title').text();
document.title = newTitle;
if(savePushState){
var obj = { Title: newTitle, Url: target };
window.history.pushState(obj, obj.Title, obj.Url);
}
});
});
});
}
带有远程脚本的页面链接,特别是 datatables.net 有时不起作用。请进行任何调整以使其运行顺畅。
解决方案
你遇到的问题是你还没有真正考虑过依赖管理。你有一个优雅的改变页面的方法,但是没有方法来处理这些页面在 CSS/JS 方面的要求。
有各种各样的教程,甚至是管理这类事情的框架。您可以做的一件事是预先声明每个有效路由(即页面)的依赖关系,然后在调用路由时加载它们。
由于您加载的 HTML 在正确显示之前似乎依赖于 JS,因此我们将强制插入 HTML 以等待任何和所有 JS 依赖项加载。
const routes = {
'page1.html': {
js: ['https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js'],
css: ['https://guidecore.xyz/assets/css/main.css']
}
/* ... */
};
const pageContent = $('.page-content'); //<-- let's cache this element
function loadPage(target, savePushState) {
pageContent.fadeOut(function() {
//let's load dependencies
const promises = [];
['js', 'css'].forEach(type => {
routes[target] && (routes[target][type] ?? []).forEach(uri => {
if (type == 'js')
promises.push(fetch(uri)
.then(response => response.text())
.then(code => {
const el = document.createElement('script');
el.textContent = code;
document.body.appendChild(el);
})
);
else {
const el = document.createElement('link');
el.href = uri;
el.rel = 'stylesheet';
document.head.appendChild(el);
}
});
});
//wait for JS dependencies to load before we get new HTML
Promise.all(promises).then(() => {
$('body').load(target, function(data) {
pageContent.fadeIn(function(){
let newTitle = $(data).filter('title').text();
document.title = newTitle;
if(savePushState) {
var obj = { Title: newTitle, Url: target };
window.history.pushState(obj, obj.Title, obj.Url);
}
});
});
});
});
}
loadPage('page1.html');
推荐阅读
- python - python3中的错误(TypeError:'module'对象不可调用)
- python - 将数据框列中的一个字符串列解析为许多其他列
- elasticsearch - 如何按降序对kibana索引进行排序?
- java - Java 中的错误:org.postgresql.util.PSQLException: ERROR: syntax error near ;
- python - 从 python 请求结果中检索单个 json 对象作为列表
- hl7-fhir - fhir 中的 Inventory Item MFN M15 消息
- html - CSS:移动“border-radius 50%”-向上循环 2px?
- c++ - 连续数组的第 K 个最大和
- azure-devops - 如何过滤添加相关工作项的结果
- python - 删除 x 值时的数组组合