简体   繁体   中英

Ignore CSS when loading external HTML file with AJAX

I am building a webpage and I am using a javascript function to get an HTML file and show the content of it.

http://progress.cat/portfolio.html -> where main HTML is

http://progress.cat/portfolio_js.html -> getting HTML from this page (to be placed in portfolio.html)

The problem is my portfolio.html main CSS

http://progress.cat/assets/css/particle_dark.css

http://progress.cat/assets/css/particle_demo.css

is being mixed with my portfolio_js.html css

http://progress.cat/portfolio_logic/css/freelancer.min.css

What I want is portfolio_js to ignore the main CSS

How it looks

How it should look

Is this possible?

Function :

  function includeHTML() {
  var z, i, elmnt, file, xhttp;
  /*loop through a collection of all HTML elements:*/
  z = document.getElementsByTagName("*");
  for (i = 0; i < z.length; i++) {
    elmnt = z[i];
    /*search for elements with a certain atrribute:*/
    file = elmnt.getAttribute("w3-include-html");
    if (file) {
      /*make an HTTP request using the attribute value as the file name:*/
      xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4) {
          if (this.status == 200) {elmnt.innerHTML = this.responseText;}
          if (this.status == 404) {elmnt.innerHTML = "Page not found.";}
          /*remove the attribute, and call this function once more:*/
          elmnt.removeAttribute("w3-include-html");
          includeHTML();
        }
      }
      xhttp.open("GET", file, true);
      xhttp.send();
      /*exit the function:*/
      return;
    }
  }
};

First of all, I'd recommend you include this partial snippet on the server-side rather than with ajax. For example, if you're using PHP, it would be like: <?php include 'some_file.html'; ?> <?php include 'some_file.html'; ?>

But if you're going to use ajax, then the external file you want to get should not include anything except for the raw HTML you're trying to get. It shouldn't have any other tags. No <html> , <head> , etc. Any stylesheets it needs should be loaded onto the main page.

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