0

In my question from yesterday, I asked how to retrieve the full HTML content as text. Seems like XHR is the way. Now, however, I have a different problem.

I use this code to retrieve the content of the document as a string:

var req = new XMLHttpRequest();
req.open("GET", document.location.href);
req.onreadystatechange = function () {
    if (req.readyState === 4 && (req.status === 200 || req.status == 0)) {
        console.log(req.responseText);
    }
};

req.send(null);

However, there is a slight delay that I'd like to avoid. I'm testing on localhost and Chrome DevTools says there's several milliseconds of "Stalled" time. In the "Size" column, it says "(from disc cache)", so I know I'm requesting something that the client already has.

Questions

  • Since the request is about something that already exists, can I somehow make the response instantaneous?

  • Can I access the original request (the one that is fired after typing the website URL) and access its response text?

My goal is to get the document as a string as soon as possible and without waiting for the DOM to load.

Community
  • 1
  • 1
dodov
  • 5,206
  • 3
  • 34
  • 65

1 Answers1

0

You could implement a cache:

function retrieve(url,callback){
 if(localStorage.getItem(url)){
    return callback(localStorage.getItem(url));
}

   var req = new XMLHttpRequest();
  req.open("GET", document.location.href);
  req.onreadystatechange = function () {
  if (req.readyState === 4 && (req.status === 200 || req.status == 0)) {
    localStorage.setItem(url,req.responseText);
    callback(req.responseText);
 }
};
req.send(null);
}

retrieve("http://test.com",console.log);//takes its time
setTimeout(retrieve,1000,"http://test.com",console.log);//should be very fast...

Also if you want to get the current response, why dont you simply access the document bject?

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • The `document` doesn't contain all the data until the DOM has loaded. I need the text ASAP. I don't want to wait for anything to load except for the script that processes the text (which would be at the top of the ``). – dodov May 08 '17 at 11:56