加载页面无需重新加载的最佳方式

时间:2017-08-31 01:15:16

标签: javascript jquery html css ajax

我正在建立一个网站,每次按下链接时都不会重新加载到新页面。我想做一些类似所有企业/热门网站的东西。 (查看网络开发标签时:请注意,当您点击链接时,youtube页面不会完全重新加载,与谷歌相同,大部分都与Facebook相同。他们通常只是重新加载页面内容而不是其他内容。)

我想只更改body标签之间的HTML(没有别的:没有js,css,没有head标签等)。

看起来很容易。目前,我只是使用ajax出去获取页面的html,并将其加载到正文中。完成!不是那么快......三件事(我的代码在底部)

  1. js包含位于页面底部,就在关闭正文和html标记之前。查看网络选项卡时,它显示始终再次获取相同的js并再次进行解析。我该如何预防呢?

  2. 某些页面不会加载已设置的样式。 (请注意,每个页面的所有css,js等脚本都相同)

  3. 我想确保在用户离开网站时完全重新加载页面。

  4. 我不确定我是否正在寻找修复方法,但可能只是采用完全不同的方式。

    这是我的代码:

    $('a').on('click', function () { //on click of any <a> tag
        var where = $(this).attr('href'); //gets url of the <a> attribute
        $.ajax({
            type: "GET",
            url: where, //where is the variable defined above
            success: function(a) {
                // load next page
                history.pushState({urlPath: where},"",where); //changes the link of the webpage
                $('body').html(a); //changes the body of the webpage
                document.title = $('#title').text(); //changes the title using some weird irrelevant method
            }
        });
        return false;
    });
    $(window).on('popstate', function() {//on click of the back or forward button
        $.ajax({
            type: "GET",
            url: window.location.href, //the url is the url that the back or forward button is set to
            success: function(data) {
                //console.log();
                $('body').html(data);//replaces data
                document.title = $('#title').text();//changes title using weird irrelevant method
            }
        });
    });
    

0 个答案:

没有答案
相关问题