4

The following code results in an HTTP request for an image resource in both Firefox and Chrome.

var el = document.createElement('div');
el.innerHTML = "<img src='junk'/>";

As a programmer, I may or may not want el to be rendered. If I don't, then maybe I don't want a request being sent for the src.

dojo.toDom() shows the same behaviour.

Is there anyway to get a document fragment from a string, without referenced resources from being requested?

Dancrumb
  • 25,148
  • 10
  • 67
  • 128

2 Answers2

2

Use the DOMParser to create a full document structure from a given string.

Alternatively, use the beforeload event to intercept requests.

Community
  • 1
  • 1
Rob W
  • 328,606
  • 78
  • 779
  • 666
  • PS. Demo for method 1: http://jsfiddle.net/4rkUU/. Method 2 is only available to Webkit extensions. – Rob W Apr 26 '12 at 18:54
-2

Much lighter memory to use strings to create DOM elements instead of creating documentFragments and working with them:

var div = document.createElement('div');
div.innerHTML = 'some text';
document.getElementById('someparent').appendChild('div');

Can be replaced with:

var div = '<div>some text</div>';
document.getElementById('someparent').innerHTML += div;
Adam
  • 46,658
  • 11
  • 63
  • 84