Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing invalid HTML with jQuery, without adding to DOM?

Tags:

jquery

dom

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.

like image 713
Jamie Treworgy Avatar asked Oct 10 '22 15:10

Jamie Treworgy


1 Answers

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

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

like image 76
SLaks Avatar answered Oct 20 '22 06:10

SLaks