Welcome!

Welcome to the official BlackBerry Support Community Forums.

This is your resource to discuss support topics with your peers, and learn from each other.

inside custom component

Web and WebWorks Development

Reply
Trusted Contributor
chicoxml
Posts: 227
Registered: ‎09-03-2010
My Device: Not Specified
Accepted Solution

appendChild vs innerHTML

which one do you choose and tell me why?

 

<script type="text/javascript">

window.onload = function() {

	for (var i = 0; i <= 20; i++) {
		var div  = document.createElement("div");
		div.innerHTML =i;
		document.getElementById("content").appendChild(div);
	};
};

</script>
<body>
<div id="content"></div>
</body>

 

or

 

<script type="text/javascript">

window.onload = function() {


var div ="";
for (var i = 0; i <= 20; i++) {
div += "<div>"+i+"</div>"
};

document.getElementById("content").innerHTML =div;

};

</script>

<body>

<div id="content"></div>


</body>

 

Please use plain text.
BlackBerry Development Advisor (Retired)
astanley
Posts: 1,382
Registered: ‎07-02-2009
My Device: BlackBerry Bold 9900
My Carrier: Bell

Re: appendChild vs innerHTML

 

In general, appendChild is a lot faster when used responsibly. Here's a good benchmark test to test for yourself: http://jsperf.com/appendchild-vs-innerhtml2/6

 

By responsible I mean use it as long as you're not doing live DOM manipulation.  Everytime you call appendChild() on a live DOM element, it causes the browser engine to recalculate and repaint the entire page.

 

In your example, you are doing live DOM manipulation.

 

Each time the for loop iterates, it repaints the page.  You only have 20 iterations, but what if that was 20,000 ?

 

Instead, construct your entire document element aside from the live DOM, and then do a single repaint when you are finished, like this:

 

var div, container = document.createElement("div");

for (var i = 0; i <= 20; i++) {
	div = document.createElement("div");
	div.innerText = i;
	container.appendChild(div);
};

document.getElementById("content").appendChild(container);

 Make sense?

Follow me on Twitter: @n_adam_stanley
-------------------------------------------------------------------------------------------------------------------------
Your app doesn't work? Use BlackBerry remote web inspector to find out why.
Please use plain text.
Trusted Contributor
chicoxml
Posts: 227
Registered: ‎09-03-2010
My Device: Not Specified

Re: appendChild vs innerHTML

yes , you have  the reason , i'm overloading the DOM  i'm going to try change this code.

 

thanks.

Please use plain text.