1

При загрузки странички аяксом

    $.ajax({
        method: "POST",
        data: {ajax: 1},
        url: url,
        dataType: "html"
    }).done(function (data) {
        var title = $(data).filter("title").html();
        window.history.pushState('',title, url);
        var head = data.match(/<head[^>]*>[\s\S]*<\/head>/gi);
        $('head').append(head);
        $('.content').empty().html($(data).filter(".content").html());
        //$("title").html(title);
        var classes = data.match(/<body class="([\w\s-]*)"/s)[1];
        $("body").attr("class", classes + " load");

    });

Нужно подменить head-ы, а чтобы не отпадали стили во время загрузки, нужно только изменённые или добавленные элементы. Кто может подсказать как это сделать? Возможно есть способ как-то поэлементно проверить есть ли уже такой на странице по селектору, и такое-же у него содержимое или нет. Пока вижу такой выход, если не найду решения, так и буду костылять.

UPD:

function changePage(obj, e) {
    $(".current_page_item").removeClass("current_page_item");
    $(obj).closest("li").addClass("current_page_item");
    var url = $(obj).attr("href");
    $(".changer").animate({left: 0}, 500, function () {
        $.ajax({
            method: "POST",
            data: {ajax: 1},
            url: url,
            dataType: "html"
        }).done(function (data) {
            var title = $(data).filter("title").html();
            window.history.pushState('', title, url);
            var head = data.match(/<head[^>]*>([\s\S]*)<\/head>/s);
            $(".content").append("<plaintext></plaintext>");
            $("plaintext").html(head[1]);
            $("plaintext title, plaintext meta").remove();
            var supervise = [];
            $('link').each(function() {
                var txt = $(this).attr("href");
                if (supervise[txt])
                    $(this).remove();
                else
                    supervise[txt] = true;
            });
            var supervise = [];
            $('style').each(function() {
                var txt = $(this).html();
                if (supervise[txt])
                    $(this).remove();
                else
                    supervise[txt] = true;
            });
            var supervise = [];
            $('script').each(function() {
                var txt = $(this).attr("src")+$(this).html();
                if (supervise[txt])
                    $(this).remove();
                else
                    supervise[txt] = true;
            });
            $("head").append($("plaintext").html());
            $("plaintext").remove();
            $('.content').empty().html($(data).filter(".content").html());
            $("title").html(title);
            var classes = data.match(/<body class="([\w\s-]*)"/s)[1];
            $("body").attr("class", classes + " load");
            $(".changer").animate({left: "100%"}, 1000, function () {
                $(".changer").css({"left": "-100%"});
            });
        });
    });
}

Попробовал так, так как нам важно вставить только новые элементы, и важны скрипты и стили. Следующий момент - как выполнить .ready в подключённых скриптах. И как взять скрипты которые добавляются за пределами .cotnent и добавить их собственно после нашего блока контент.

1 ответ 1

1

Решил заменой всего body кроме блока что отвечает за анимацию перехода. Его не удаляю с существующего и удаляю с нового body.

function changeAjax(url) {
    console.log(0);
    if (change) return true;
    change = true;
    $.ajax({
        method: "POST",
        data: {ajax: 1},
        url: url,
        dataType: "html"
    }).done(function (data) {
        html = data;
        var title = $(data).filter("title").html();
        window.history.pushState('', title, url);
        var head = data.match(/<head[^>]*>([\s\S]*)<\/head>/s)[1];
        body = data.match(/<body[^>]*>([\s\S]*)<\/body>/s)[1];
        var myBody = $("<body></body>").html(body);
        myBody.find(".changer").remove();
        $("body :not(.changer)").remove();
        $("body").append(myBody.html());

        var myHead = $("<head></head>").html(head);
        myHead.remove("#dashicons-css,#bootstrap-css,#fontawesome-all-css,#slider-css,#style-css");
        $("head :not(#dashicons-css,#bootstrap-css,#fontawesome-all-css,#slider-css,#style-css)").remove();
        $("head").append(myHead.html());
        rebindLink();
        $("title").html(title);
        var classes = data.match(/<body class="([\w\s-]*)"/s)[1];
        $("body").attr("class", classes + " load");
        $("body").removeClass("openmenu");
        change = false;
        setTimeout(function () {
            okCut(".cut-img", 100);
        }, 300);
        $(".changer").animate({left: "100%"}, 1000, function () {
            $(".changer").css({"left": "-100%"});
        });
    });
}

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.