开发者

Parsing invalid HTML with jQuery, without adding to DOM?

开发者 https://www.devze.com 2023-03-16 12:46 出处:网络
I\'m working on a jQuery plugin that uses an HTML template. End users may pass in a template that looks at the simplest level like this:

I'm working on a jQuery plugin that uses an HTML template. End users may pass in a template that looks at the simplest level like this:

<template>
   <img src="/images/image_{field_id}.gif">
</template>

The template is supposed to be commented out, so that the browser won开发者_如何学运维't try to render anything, My code just extracts the interior of the comment as text, and then uses jQuery to parse it into an element tree. Then I do specific substitutions.

I remember reading that jQuery just uses the DOM to parse HTML, e.g. when you just do

var x = $(html_string);

jQuery is actually just adding it to the DOM to get the elements. The simple action above would not render anything (until I actually added x somewhere in the DOM), but yet this code results in the browser trying to load the image target - even if I never add it to the DOM. Here is a simple demonstration of this effect in action: http://jsfiddle.net/b5HGU/

So basically - is there any way to solve this problem? Can you create an "image" element with a known bad src tag using jQuery, but have it not load the image until you actually add it to the real DOM?

The other alternative I have is to complete all the parsing on the template, as a string, before using jQuery to construct a DOM. This is certainly doable, but in reality the template has a number of different components, and it is very convenient to use jQuery selectors to turn it into a navigable tree before outputting the parsed version. I'd have to basically write my own XML parser otherwise. Just wondering if there are any simple solutions before I do this the hard way.


Try calling $.parseXML, which should treat it as raw markup without interpreting anything.

I suspect that it will need to be well-formed.


It's very old thread, but i ran just the same problem today. I found somewhat solution for this - parsing html with jquery without loading all these assets, images etc. It's not the most elegant solution, but it works anyway.

var parser = new DOMParser();
//i assume your html-string is in resp variable
var doc = parser.parseFromString(resp, "text/html");
// here just css-select your element with standard method
var div = doc.querySelector('#mydiv');
// then you can wrap this element with jquery and do what you want
var $div = $(div);

Hope it helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消