Sign in to follow this  
BloodWarrior

JavaScript Optimisation

Recommended Posts

Heyas I have an html application that generates some elements on the fly. For example a combobox is created with document.createElement(); and then populated. My problem is that on some pages I have about 4-5 comboboxes each with hundres of elements which take forever to load. Does anyone know of a way to speed up javascript? some kind of precompile or anything else that allows the browser to process its code a lot faster. Most of it is inside a loop so it should be fairly easy to optimise. If anyone knows any particularly slow operations in javascript I would also appreciate some help here. ------------- EDIT: It seems I didnt made myself clear. Im not complaining about download times but actually about processing times. Here is a small example
<html>
<script>
function doScript()
	{
	var newCombo = document.createElement("<select>");
	for(var i=0;i<1000;i++)
		{
		var newElement = document.createElement("<option>");
		newElement.value = "i";
		newElement.innerText = "this is "+i+" option";
		newCombo.appendChild(newElement);
		}
	document.body.appendChild(newCombo);
	}
</script>
<body>
<input type="button" onclick="doScript()" value="click me">
</body>
</html>
This is a very very simple example but even then when you click on the button there is a slight delay on my machine. This is a fairly decent work machine so I can understand when clients complain that in their machines the code is too slow. Plus the original code get strings here and there and changes styles etc etc. So, does anyone know of a way to optimise javascript? ------------- Yours Truly K [Edited by - BloodWarrior on September 7, 2006 7:33:13 AM]

Share this post


Link to post
Share on other sites
It seems like you have a lot of static data on the page.

Have you tried Ajax, so that you can reduce the weight of the page, and only work on data that is relevant to the current job being performed?

Share this post


Link to post
Share on other sites
One fun way to optimize js is to remove whitespace and reduce the lenght of variable names - there's nothing like reading scripts optimized in that way ;). A syntax highlighting script I downloaded some time ago had two different versions - one normal and one without extra formatting (making it just a blob of characters). (I'm only partially serious here - it's to be concidered as a LAST resort)

[Edited by - e-u-l-o-g-y on September 7, 2006 6:21:56 AM]

Share this post


Link to post
Share on other sites
There is a free javascript app online that can compress javascript code for you. I forgot what the url is but I'm sure googling javascript compression or a variation of that can find it. Good luck.

Share this post


Link to post
Share on other sites
Quote:
Original post by T1Oracle
There is a free javascript app online that can compress javascript code for you...
By compress do you mean white-space removal, or does it actually compress the text in the page?

Share this post


Link to post
Share on other sites
ops!
Guess I didnt make myself clear...

when I meant that it took forever to load I meant the dynamic building of the combobox took forever to execute. I didnt meant that the page was downloading stuff.

Imagine that you have a page with a button. Clicking on it will trigger a script that creates and displays a combobox. However the combobox has 1000 items that are all created dynamically and so the time it takes to create this is quite long.

I will update the first post to add an example soon.

Yours Truly
K

Share this post


Link to post
Share on other sites
Quote:
Original post by e-u-l-o-g-y
It doesn't seem like an optimal solution to append all those elements.. perhaps you should look into another solution? Perhaps php is a better option or ajax like Prozak mentioned.


yeah... but ajax only allows me to retrieve information at runtime and as for php it requires that my code is held in a php enabled server.
Plus php building the page would mean that it would download the page completed (huge page then) although I could minimise it by using ajax to download only the parts that I needed when I needed them.

No... my current solution means that my pages are really small since they are a bunch of javascript data and fixed javascript builders. They work really really well except when I hit a page that has so much data that it takes a long time processing... and its really processing time.
Maybe I should get/build a javascript profiler to see exactly who is messing about with my performance and then try to dump the culprit.

oh.. wait... that comment about append... It just gave me an idea... I guess I could try to only append once by concatenating the strings for each option. Although I suspect concatenation is a slow process in javascript just as it is in any other language.

Share this post


Link to post
Share on other sites
You may find that creating a long string with some HTML in, then setting the property "innerHTML" on an existing element, is a lot quicker than creating all the DOM nodes manually (the DOM nodes may not appear instantaneously afterwards, but will be there soon).

This method works in IE, Mozilla, Opera and others. It's not an "official" W3C method however.

There may be another way of creating options for a select... maybe you can create a new option using the javascript constructor "Option" ... I think that is standard (better look that up though).

Seriously, the innerHTML method is evil, but works pretty well.

Mark

Share this post


Link to post
Share on other sites
Quote:
Original post by markr
You may find that creating a long string with some HTML in, then setting the property "innerHTML" on an existing element, is a lot quicker than creating all the DOM nodes manually (the DOM nodes may not appear instantaneously afterwards, but will be there soon).

This method works in IE, Mozilla, Opera and others. It's not an "official" W3C method however.

There may be another way of creating options for a select... maybe you can create a new option using the javascript constructor "Option" ... I think that is standard (better look that up though).

Seriously, the innerHTML method is evil, but works pretty well.

Mark


All Hail to thee Mark
check this sample. Button 1 is the correct way of doing it, button 2 is the best way but it doenst seem to work with select. Button 3 is the logical alternative to button 2 but it slows down the bigger the body becomes (click a few times and notice those times increasing). Button 4 is the best solution.

Thanks, i go on and review all of my code.
Yours Truly
K

<html>
<script>
function doScript1()
{
var start = new Date().getTime();
var newCombo = document.createElement("<select>");
for(var i=0;i<1000;i++)
{
var newElement = document.createElement("<option>");
newElement.value = "i";
newElement.innerText = "this is "+i+" option";
newCombo.appendChild(newElement);
}
document.body.appendChild(newCombo);
var end = new Date().getTime();
var time = document.createElement("
");
time.innerText="Type 1="+(end-start);
document.body.appendChild(time);
}
function doScript2()
{
var start = new Date().getTime();
var result ="";
for(var i=0;i<1000;i++)
{
result += "<OPTION value="+i+">this is "+i+" option numver</OPTION>";
}
var newCombo = document.createElement("<Select>"+result+"</select>");
document.body.appendChild(newCombo);
var end = new Date().getTime();
var time = document.createElement("
");
time.innerText="Type 2="+(end-start);
document.body.appendChild(time);
}
function doScript3()
{
var start = new Date().getTime();
var result ="";
for(var i=0;i<1000;i++)
{
result += "<OPTION value="+i+">this is "+i+" option numver</OPTION>";
}
document.body.innerHTML=document.body.innerHTML+"<Select>"+result+"</select>";
var end = new Date().getTime();
var time = document.createElement("
");
time.innerText="Type 3="+(end-start);
document.body.appendChild(time);
}
function doScript4()
{
var start = new Date().getTime();
var result ="";
for(var i=0;i<1000;i++)
{
result += "<OPTION value="+i+">this is "+i+" option numver</OPTION>";
}
var newCombo = document.createElement("
");
newCombo.innerHTML="<Select>"+result+"</select>";
document.body.appendChild(newCombo);
var end = new Date().getTime();
var time = document.createElement("
");
time.innerText="Type 4="+(end-start);
document.body.appendChild(time);
}
</script>
<body>
<input type="button" onclick="doScript1()" value="click me1">
<input type="button" onclick="doScript2()" value="click me2">
<input type="button" onclick="doScript3()" value="click me3">
<input type="button" onclick="doScript4()" value="click me4">
</body>
</html>

Share this post


Link to post
Share on other sites
Quote:
Original post by BloodWarrior
ops!
Guess I didnt make myself clear...

when I meant that it took forever to load I meant the dynamic building of the combobox took forever to execute. I didnt meant that the page was downloading stuff.

Imagine that you have a page with a button. Clicking on it will trigger a script that creates and displays a combobox. However the combobox has 1000 items that are all created dynamically and so the time it takes to create this is quite long.

I will update the first post to add an example soon.

Yours Truly
K


Use a timed creation.. Writing the text to the box at 100ms intervals.

Share this post


Link to post
Share on other sites
Create all of the elements you might need when the page is first created (onLoad) and then just add them to the appropriate element when the action is invoked that requires dynamically adding elements to the page. The loading will be longer but using the page will be much faster.

Share this post


Link to post
Share on other sites
Quote:
Original post by jregan
Create all of the elements you might need when the page is first created (onLoad) and then just add them to the appropriate element when the action is invoked that requires dynamically adding elements to the page. The loading will be longer but using the page will be much faster.


tried that... but unfortunately clients want both instant download on anything down to a k56 modem AND they want instant processing in the pages.

Ah well, regardless I did manage to find a solution (its above) and it works quite well.
Thanks for all the input.

Share this post


Link to post
Share on other sites
Are you sure you're trying to solve the right problem here? If you're just generating the list of options clientside without having to download anything, the list couldn't be much more than a list of numbers, right? It seems to me that having a combo box filled with hundreds of ordered numerical options is bad UI design in the first place. If you just want to input a number, why not use a text field? Instead of "pick a number from 1 to 1000 from this really huge, slow, and hard-to-navigate combo box", you would have "enter a number from 1 to 1000 in this text box." [smile]

It would be much cleaner, faster, easier for the end user, and it wouldn't require all that messy javascript. I don't think you've mentioned why you're using this approach - is there some reason you have to use combo boxes instead of the simpler and easier option?

Share this post


Link to post
Share on other sites
1) First, consider what MrAccident said.
2) Second, see what you can do server-side. It makes a lot more sense to do the loop in a server-side application (which only has to produce the actual HTML data, rather than re-render things after each added number), and then send a form to the user with the HTML text all static. The server will likely zip the HTML for transport anyway, so it won't really be that bad for download (it's only a few Kb anyway for 1000 numbers), and then the browser can account for all the numbers at once instead of having to refresh things every time the javascript loop iterates.
3) As a last resort, consider anything else that was said here - it's good advice for the problem, but please make sure you address the right problem first.

Share this post


Link to post
Share on other sites
Quote:
Original post by Prozak
Quote:
Original post by T1Oracle
There is a free javascript app online that can compress javascript code for you...
By compress do you mean white-space removal, or does it actually compress the text in the page?

It removes white space and shortens variable names. I just found the tool, check it out.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this