最简单的SPA(单页应用)实现

 

$(function(){
    var replacePage = function(href, onFinish){
        $.get(href,{},function(raw){
            var data = raw.substring(raw.indexOf('</head>')+7,raw.indexOf('</body>')+7);
            $('body').html(data);
            if(onFinish!=undefined)onFinish();
        });
    };
    $("body").click(function(){
        var $target = $(event.target);
        var href = $target.attr('href');
        if(href=="")return;

        event.preventDefault();
        console.log('SPA push',href);
        replacePage(href, function(){
            history.pushState(null,null,href);
        });
    });
    window.addEventListener('popstate',function(event){
        console.log('SPA pop');
        replacePage(window.location.href);
    });
});

 

posted @ 2016-08-05 12:31  fzyzcjy  阅读(375)  评论(0编辑  收藏  举报