Reputation: 84
I am fetching a remote page's HTML and returning the HTML to review meta tags and I notice unexpected failed requests for all the remote assets in the other page's HTML whenever I assign that to a variable.
$.get(url, function(data, status) {
var dt = $(data);
}
By the time I've assigned that variable, it triggers all these remote requests.
How can I avoid the the fact that assigning this data to a variable in the DOM seems to trip a request for every image or resource on that remote page!
Upvotes: 0
Views: 81
Reputation: 207521
When you do $(data)
, jQuery ends up parsing the hTML and causes the requests to be made for the resources.
To get around it, use DOM parser so the resources are not fetched.
const myHTMLSource = `
<html>
<head>
<meta name="title" content="Foo Bar">
<meta name="description" content="FOO FOO">
<meta name="keywords" content="bar, egg, bacon">
<meta name="robots" content="index, follow">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="language" content="English">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"><\/script>
</head>
</body>
<h1>Test</h1>
<img src="http://placekitten.com/200/300" />
</body>
</html>`;
const parser = new DOMParser();
const testDoc = parser.parseFromString(myHTMLSource, "text/html")
const metaTags = testDoc.querySelectorAll("meta");
console.log(metaTags.length);
Since being asked how to use in in the jQuery Ajax request, it just uses data:
var request = $.ajax({
url: url,
method: "GET",
dataType: "text"
}).done(function( data ) {
const parser = new DOMParser();
const testDoc = parser.parseFromString(data, "text/html")
const metaTags = testDoc.querySelectorAll("meta");
console.log(metaTags.length);
}).fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
Upvotes: 1
Reputation: 178026
So you claim: GETTING the html results in the requests inside the result are executed when doing $(data)
. So the issue is to NOT use $(data)
but the raw HTML but that means some kind of split on </head>
BEFORE creating a DOM fragment
Try this:
Uncomment the comments and remove the string I use for testing
//$.get(url, function(data, status) { // uncomment
// const dt = data.split("</head>")[0]
const fragment = document.createElement("div");
// fragment.innerHTML = dt;
// test
fragment.innerHTML = `<html>\n<head>\n<meta name="title" content="Foo Bar">\n<meta name="description" content="FOO FOO">\n<meta name="keywords" content="bar, egg, bacon">\n<meta name="robots" content="index, follow">\n<meta http-equiv="Content-Type" content="text/html; charset=utf-8">\n<meta name="language" content="English">\n<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"><\/script>`;
[...fragment.querySelectorAll("meta")]
.forEach(meta => {
console.log([...meta.attributes]
.map(attr => `${attr.nodeName}: ${attr.nodeValue}`))
})
//}}
Upvotes: 0