Julien Genestoux
Julien Genestoux

Reputation: 33012

How does $('<html><head>...</head><body>...</body></html>') work?

I am still trying to create a full DOM document from a string. I got a bunch of interesting suggestions on this other question, but none actually fits what I'm looking for. So I'm trying to understand how things work to maybe find a solution.

We need to replace a lot of JQuery code with 'native' Javascript. With Jquery, we are able to do $('<html><head>...</head><body>...</body></html>') and then perform operations on the nodes of this object, search them... etc.

What does Jquery do? Does it create a new document? Append to the existing one?

Since a lot of people question our replacement of Jquery, here is a little more details: we are building a chrome application which will make use of content script. Even if Jquery is lightweight, it's not very kind of us to add a couple MB of memory consumed in each tab for a very few Jquery methods. Jquery is awesome and fits many many needs, not ours.

Upvotes: 0

Views: 195

Answers (2)

Gijs
Gijs

Reputation: 5262

You can find your answer in the jQuery source. You start out with core.js, where you'll find the init method. If you follow the logic there, you'll see that for any nontrivial elements it'll call jQuery.buildFragment, which indeed builds a DocumentFragment which it'll populate with the content you specified. That will teach you how to deal with building a DOM tree from a string, including stripping out various bits of content that you most likely won't want.

Upvotes: 1

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385274

jQuery is open-source, so see for yourself.

Looks like it uses a combination of createElement and createDocumentFragment, depending on a few things.

So you cannot use jQuery but you can re-invent it? Seems strange. Try to lose this bizarre requirement.

Upvotes: 1

Related Questions