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
  • 26,597
  • 10
  • 74
  • 130

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
  • 341,306
  • 83
  • 791
  • 678
  • 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 Jenkins
  • 51,445
  • 11
  • 72
  • 100