首页 > 解决方案 > 加载新网页而不重新加载加载脚本错误

问题描述

我正在尝试让 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 有时不起作用。请进行任何调整以使其运行顺畅。

标签: javascripthtmljqueryajax

解决方案


你遇到的问题是你还没有真正考虑过依赖管理。你有一个优雅的改变页面的方法,但是没有方法来处理这些页面在 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');

推荐阅读