dom - Javascript: Replace Element vs Change Element Property -
while reading image lazy loading script, noticed there such operations(comments added me):
function loadimage (el) { var img = new image() , src = el.getattribute('data-src'); img.onload = function() { if (!! el.parent) el.parent.replacechild(img, el) // replace element else el.src = src; // change element property } img.src = src; }
why not change element property? simpler. why create new element , replace old element (both elements images,anyway)? advantages?
function loadimage (el) { src = el.getattribute('data-src'); el.src = src; // change element property }
it done way provide off-screen loading , browser efficiency purposes (though specific implementation flawed in regard).
it seems lazy loading wants actual loading of image happen "out of view". so, reason, new image object created , .src
set on that.
then, once new image has been loaded, more efficient browser use new image object rather change .src
on image in dom. so, if image appears in @ least dom fragment (e.g. if has parent), new image swapped place , thing browser has dom operation , repaint.
if image has no parent, there no way swap out original, sets .src
on it. setting .src
property cause browser request image url again. find url in local cache, still have image cache , parse image format (which more work swapping dom element).
it appears reference el.parent
in code should el.parentnode
. if go lazyloading demo page , set breakpoint in own code, never .replacechild()
option of if
statement because el.parent
not standard dom property , undefined
in browsers tried - chrome, firefox, ie11 , edge.
Comments
Post a Comment