简体   繁体   中英

JS loading external HTML that should load the HTML's assets (CSS and JS)

I've written the snippet below to send an HTTP request to get an HTML file. The HTML file has CSS and JS included (link and script tags):

var request = new XMLHttpRequest();
request.open('GET', 'form.html', true);

request.onload = function() {
  if (request.status >= 200 && request.status < 400) {
    var resp = request.responseText;

    this.innerHTML = resp;
  } else {

  }
};

request.onerror = function() {

};

request.send();

The above snippet sends a request and gets the HTML. However, it's having problems putting the HTML into the DOM and it's not sending requests to fetch the styles and javascript. How can I do the above and take the response HTML, put it into the page, and have it send the requests to get the various assets?

In your onload handler, this refers to the request object, not the document, so setting the innerHTML property won't do anything useful. You need to tell it where to put the new HTML, eg

request.onload = function() {
  if (request.status >= 200 && request.status < 400) {
    var resp = request.responseText;

    document.documentElement.innerHTML=resp;
  } else {

  }
}

(Note this won't work in early IE versions)

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