简体   繁体   中英

Combine pAjax with assets loading

I'm using ajax to load a new page when user clicks a link on a page, and using HTML history push state for changing title, no problem there. There is a "loading bar" on top so user knows something is going on.

What I'd like to achieve is to replace a page once all assets from ajax loaded page are loaded, now on .done() I'm replacing only html string that's returned.

Site is image-heavy so I'm forced to: a) load page with ajax (which is fairly quick) b) when html is replaced, I need to show new "preloader" to actually load all assets

I would like to avoid doing b) thing.

Code:

$.ajax({
    url: "urltoload.html",
    context: document.body
}).done(function(data) {
    var newDoc = document.open("text/html", "replace");
    newDoc.write(data);
    newDoc.close();
});

I am replacing full page (including scripts), as loaded page is full of assets (large images), I'm using this great tool waitForImages for loading all assets before really showing a page.

So first I load page with ajax, then when page is replaced I load images to show page. I would like to merge it onto one loading.

Append this to to your index.html page in body tag.

<body onload="loadcontent()">

And this to js part (Replace "YourContentFileUrl.html" in the below code with the file url to be fetched via ajax request):

function loadcontent() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
       document.open();
    document.write(xhttp.responseText);
    document.close(); 
    }
  };
  xhttp.open("GET", "YourContentFileUrl.html", true);
  xhttp.send();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM