HTML JavaScript delay downloading img src until node in DOM -


hi have markup sent me server , set innerhtml of div element purpose of traversing tree, finding image nodes, , changing src values. there way prevent original src value being downloaded?

here doing

function replaceimagesrcsinmarkup(markup) {   var div = document.createelement('div');   div.innerhtml = markup;   var images = div.getelementsbytagname('img');   images.foreach(replacesrc);   return div.innerhtml; } 

the problem in browsers do: var img = document.createelement('img'); img.src = 'someurl.com' browser fires off request someurl.com. there way prevent without resorting parsing markup myself? if there in no other way know way of parsing markup little code possible accomplish goal?

i know happy solution, think worth sharing safe method future users.

you can use domparser object generate external document html string, instead of using div created current document container.

domparser avoids pitfalls mentioned in question , other threats: no img src download, no javascript execution, in elements attributes.

so in case can safely do:

function replaceimagesrcsinmarkup(markup) {     var parser = new domparser(),         doc = parser.parsefromstring(markup, "text/html");      // manipulate `doc` regular document     var images = doc.getelementsbytagname('img');      (var = 0; < images.length; += 1) {         replacesrc(images[i]);     }      return doc.body.innerhtml; } 

demo: http://jsfiddle.net/94b7gyg9/1/

note: current code, browsers still try downloading resource specified in img nodes src attribute, if change before end of js execution. trace network transactions in demo: http://jsfiddle.net/94b7gyg9/


Comments

Popular posts from this blog

yii2 - Yii 2 Running a Cron in the basic template -

asp.net - 'System.Web.HttpContext' does not contain a definition for 'GetOwinContext' Mystery -

mercurial graft feature, can it copy? -