We available for hire! — Need help with a web or mobile project?
From yensdesign we develop technology projects based on web apps, mobile apps, consulting and databases. We are young and hard workers, passionate about innovation and focused in new technologies.If you want to ask for a budget, we hare available for hire!.
How to create a stylish loading bar as Gmail in javascript
November 17th, 2008Hi folks! long time ago from last tutorial, eh? Sorry for that but now you know that I spent last days working hard on plusmusica.com a new online jukebox (for people who love music you know ). If you want to try it I will give you some invitations for the private beta to get feedback from you (post in comments!).
Well, let’s focus on the new tutorial called: “How to create a stylish loading bar as Gmail in javascript“. As you can suppose it will be about how to create the famous loading bar from gmail or other sites as tuenti.com (“the spanish facebook“), etc.
But the magic on this tutorial isn’t the loading bar, it’s the way to load all resources like javascript, css, and other static files that our web application will need, to delete user waiting times during his visit.
You can test a working live example over here:
Tested in: Firefox, Internet Explorer 6 & 7, Opera, Safari & Chrome.
As always, the rest of the tutorial after the jump
Thinking about the utility
For example let’s think about an autocompletation input text box that suggests to the user some cities from an array stored in an external javascript file. If we load it before the webpage the user won’t wait for the “cities.js” loading process.
You know, it’s the same for css files, and other kind of external files that our web applitacion will need along the visit.
So now that we know how this tutorial can help us, let’s dive into it.
Step 1: Building the simple and clean xhtml layout
As always, We begin the process making the layout to add the javascript magic at the end (in this example we won’t need jQuery library). We will horizontal & vertical align our loading bar with a little text showing us wich js file is being load in each moment:
[sourcecode='html'][/sourcecode]LOADING0%
 
Allright guys, so we have 2 main divisions: restart & loadingZone. We will hide at the begining the restart division and show the loadingZone, updating it while the external javascript files are loading in the process.
Note: the “ ” in the progressBar makes visible the division.
Step 2: Adding some style to our loading bar
This point is very interesting in this tut, We will learn how to make up a loading bar contained in another parent division, showing the loading process. Here comes the tip:
The division called loadingBar with a fixed width will contains the progressBar that show the status of the loading process by increasing his width % from 0% to 100%.
As always we make it easy and try to do cross browsing examples adding some tricks to IE 6 like the “overflow: hidden” to the progress bar.
So here we have the css code:
[sourcecode='css'] html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, font, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td { border:0pt none; font-family:inherit; font-size:100%; font-style:inherit; font-weight:inherit; margin:0pt; padding:0pt; vertical-align:baseline; } body{ background:#fff none repeat scroll 0%; font-size: 12px; font-family:tahoma,arial,sans-serif; margin:0pt; height:100%; } table { border-collapse:separate; border-spacing:0pt; } caption, th, td { font-weight:normal; text-align:left; } blockquote:before, blockquote:after, q:before, q:after { content:""; } blockquote, q { quotes:"" ""; } a{ cursor: pointer; text-decoration:none; } .clear{ clear:both; } #button{ text-align:center; margin:50px 50px 150px 50px; } #restart{ display:none; text-align:center; } #loadingZone{ margin:0 auto; width:410px; text-align:center; } #loadingBar{ border:1px solid #c2c2c2; height:2px; text-align:left; line-height:0; margin:0; padding:0; overflow:hidden; /*fix for IE 6*/ } #progressBar{ height:2px; line-height:0; margin:0; padding:0; background:#b3f83d; width:0%; } #loadingSms{ color:#6ea1fa; float:left; padding:10px 2px; } #infoProgress{ color:#6ea1fa; float:right; padding:10px 2px; } #infoLoading{ padding:10px; color:#b9b9b9; font-size:10px; } [/sourcecode]
As you can see we have a little more info about the loading process by adding some text division to show the % (infoProgress) and the current loading file (infoLoading).
Step 3: Here comes the javascript magic one more time
Last step and the most important on this example, we will do a lot of things with generic javascript, because we don’t need to load all jQuery library to load some external js in cache, right? Checkout this list:
- Vertical & horizontal align loading bar
- Load external javascript files as gmail does
For vertical & horizontal align the loading bar We can reuse our code to center popup that we learned in the old tutorial How to create a stunning and smooth popup using jQuery tutorial.
So create a javascript file called “loading.js” for example. We will create the loading bar class to manage all the loading process by using some methods that we will create for it:
[sourcecode='javascript'] var LoadBar = function(){ this.value = 0; this.sources = Array(); this.sourcesDB = Array(); this.totalFiles = 0; this.loadedFiles = 0; }; [/sourcecode]
So now let’s add the methods to the LoadBar class:
[sourcecode='javascript'] //Show the loading bar interface LoadBar.prototype.show = function() { this.locate(); document.getElementById("loadingZone").style.display = "block"; }; //Hide the loading bar interface LoadBar.prototype.hide = function() { document.getElementById("loadingZone").style.display = "none"; }; //Add all scripts to the DOM LoadBar.prototype.run = function(){ this.show(); var i; for (i=0; i= 0 && value <= 100){ document.getElementById("progressBar").style.width = value + "%"; document.getElementById("infoProgress").innerHTML = parseInt(value) + "%"; } }; //Set the bottom text value LoadBar.prototype.setAction = function(action){ document.getElementById("infoLoading").innerHTML = action; }; //Add the specified script to the list LoadBar.prototype.addScript = function(source){ this.totalFiles++; this.sources[source] = source; this.sourcesDB.push(source); }; //Called when a script is loaded. Increment the progress value and check if all files are loaded LoadBar.prototype.loaded = function(file) { this.loadedFiles++; delete this.sources[file]; var pc = (this.loadedFiles * 100) / this.totalFiles; this.setValue(pc); this.setAction(file + " loaded"); //Are all files loaded? if(this.loadedFiles == this.totalFiles){ setTimeout("myBar.hide()",300); //load the reset button to try one more time! document.getElementById("restart").style.display = "block"; } }; [/sourcecode]
So complex? Nah, calm down and read it one more time carefully, it's very easy (as always do over here man!) and it will be awasome for our web applications
And to finish our code, We will control by using 2 functions: start() and restart() the begin & end of the process. We will add too a little improvement to the centering function.
[sourcecode='javascript'] //Global var to reference from other scripts var myBar = new LoadBar(); //Checking resize window to recenter window.onresize = function(){ myBar.locate(); }; //Called on body load start = function(){ myBar.addScript("jsfile2.js"); myBar.addScript("jsfile3.js"); myBar.addScript("jsfile4.js"); myBar.addScript("jsfile1.js"); myBar.addScript("jsfile5.js"); myBar.addScript("jsfile6.js"); myBar.addScript("jsfile7.js"); myBar.addScript("jsfile8.js"); myBar.run(); }; //Called on click reset button restart = function(){ window.location.reload(); }; [/sourcecode]
It's usefull to use onresize javascript event to reconfigure your layout values when the user resizes his window's browser.
And that's all guys, now we will create some js files to test our example and to notify to the myBar instance class of LoadBar that some js files were loaded:
[sourcecode='javascript'] setTimeout("myBar.loaded('jsfile7.js')", 500); [/sourcecode]
myBar.loaded IT'S VERY IMPORTANT it warns to our class LoadBar that the "jsfile7.js" is complete loaded. The second value (in this example 500) is the miliseconds to simulate the waiting for loading an external js file, to let us to test our loading bar.
Finally, thats all
Step 4:Trying our stylish loading bar!
And that’s all guys, I hope this tutorial helps you. You can try the tutorial online here to see how It is working and download here all sources.
If you see bugs, bad english, got questions or something tell me by using comments, and remember to post comments for get your plusmusica.com invitation.
See you next time guys!
In order to optimize your experience and provide you with accurate information, we offer best quality SY0-201 tutorials mainly focusing on how to create loading bar in javascript. Learn about useful web applications using 640-802 guide and 350-001 live demo
Enjoy this post?
Your vote will help us to grow this website and write more entries like this one :)
We available for hire! — Need help with a web or mobile project?
From yensdesign we develop technology projects based on web apps, mobile apps, consulting and databases. We are young and hard workers, passionate about innovation and focused in new technologies. We try to help you, sharing our knowledge acquired on worked projects, while helping the community and showing our capabilities.If you want to ask for a budget, we hare available for hire! Don't doubt in get in touch with us!.
As always, a great tutorial!
Thanks you Javier!
Nice tutorial. I like the last one more though
Great tutorial ! But how to call the preloader for CSS and Images ?
Thanks Mike! In this tutorial we just show you how to load javascripts becuase is the most easy way. If you want to load CSS, you must change the “run” method:
var head = document.getElementsByTagName(“head”)[0];
var css = document.createElement(“link”);
css.type = “text/css”;
css.rel = “stylesheet”;
css.href = “[FILE]“;
head.appendChild(css);
As you can see, is easy, the complex is in how check when the file was loaded. You can do it creating a funcion that check if the css was applied and calling it each 300 miliseconds (for example). If people are interested, we can post a mini tutorial explaning it fully.
In the case of loading images, I have not tested it but I think that could be done using a iframe.
I hope this information can be useful for you.
Bye!
Well, thanks
Nice Tutorial. Thanks.
Why do you do:
html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em,
font, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody,
tfoot, thead, tr, th, td {
and not “* {“?
Anyway, great tutorial! Thanks for sharing your knowledge!
Hi Pandafox thanks for your comment!
I saw it long time ago in a reset css sheet and I use it always because in some old browsers * doesn’t works.
@Pandafox Using * would also reset form elements input, textarea, select, etc.
http://meyerweb.com/eric/thoughts/2008/01/15/resetting-again/#comment-300382 and the following comments touch on the topic.
Hi, I would like to test the website Could you sent an invitation?
Great post, thanks!
Thanks misha! Here you have your invitation Enjoy it!
very usefull thanks
you say we was gonna do this wiv JQuery but i ain’t seein no jquery!
what is prototype? why there is prototype when u is sayin jquery??
Prototype is a property not the javascript library
Hey Adrian,
Thanks this was cleverly done and it’s really a nice tutorial, just wanted to ask that, do you think of a way to achieve the same effect without putting “myBar.loaded” at the end of each loaded file?
As you know, some external files such as jquery plugins or other third party stuff should be updated from time to time. After updating those then we have to remember that we had a nice loader, which needs a small function to be run after each included file, and we have to put that function to each updated file’s bottom line again.
And about adding css i didn’t try it though, but it seems when we add a css file it will add but it won’t show it on the progressbar or am i wrong?
regards.
@Sinan Hi and thanks for posting!
As you can see, we are using myBar.loaded to have a callback response so in this case we need it.
You are right, in this example we are only loading javascript files not other kind of resources. Me and Ivan are searching to a new method to load all kind of resources but it isn’t ready. We will publish a new tutorial asap we got new info about it
Any plans of making a “preload images and javascript”-tutorial? Im trying to change this script to work, but i just keep screwing up
@Kausti I as said we are trying to find a cool way to achieve the preloading images… but nothing at this moment :S
[...] View Tutorial Share this post: Share this post with the world. [...]
not very good at javascript…
Does anyone know how to use this effect for iframe loading?
thanx
Hi there. am am trying to get my head around making this work for Images and css files but my Java skills are very lax. I have the source files for this tutorial, could anyone please help me with what i would need to enter for this to load images and css and where it would go in the JS. I would really appreciate it.
Thank you
you are great!!!
@godzalli44 Thank you so much
Can anyone help at all?
good website, nice tutorial,great author
Is there a way to use this wonderful progress bar to show while I am fetching rows from a database instead of loading files? I have some queries that run about 15 seconds (its a pretty good size calculation) and would like to display your bar while the script is getting the data.
[...] ideas were taken from jQuery 页面载入进度条 and How to create a stylish loading bar as Gmail in javascript [...]
[...] View Tutorial No Comment var addthis_pub=”izwan00″; BOOKMARK This entry was posted on Monday, June 8th, 2009 at 4:09 am and is filed under Javascript Tutorials. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site. [...]
Brilliant example!
how would I redirect to another page upon successful loading, and how would the loadbar fade out at 100%?
thanks
Learning Spanish is not so hard, especially now, when you find all kind of “learn spanish” DVD’s.
Very nice tutorial.
Thank you.
Regards,
RaphaelDDL
Hi Javier,
with great intrest I read this tutorial. Through understood nothing.
Don’t worry, its totally my fault. I am a very alogical person and have very little feel for all this letters and brackets etc. But I managed to make two websites with the visivag frontpage.
One is http://www.LisaPrice.info
On Stilllife I have a slideshow that takes long to download, i think it has to do with the resolution of the pictures. I will work on this later, but now I want to past this loading bar under or next to the picture.
Unfortunately I am completely overwhelmed with your scripting and woould like to ask you if you can give me a -lets call it template, that i can paste into my site and done.
The site is really small and easy,
Thanks so much in advance,
cheers,
Lisa
perfect share.
Hey,
i would like to load all my .css, .js, .gif and .jpg Files.
How i can do this?
Thanks, for your help!
Hi,
has anybody any idea why the “loading bar” script doesn’t work here:
http://www.cthaele.de/jquery_labs/
Thanks, for helping!
Really nice coding here, keep up the good work!
Instead of naming writing all the tags like this..
html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, .. { }
I think you can just do:
* { }
it’s so nice style but olny work with ff not ie
any way thank you
[...] Resource: Sample | Tutorial [...]
[...] Resource: Sample | Tutorial [...]
[...] Resource: Sample | Tutorial [...]
Hi,
Thanks for the great tutorial,but i am a bit confused about the setTimeout(“myBar.loaded(‘jsfile1.js’)”, 500); part. Do i need to put this code at the end of my code in that file eg. suppose jsfile1.js contain
var ni = document.getElementById(‘myDiv’);
var numi = document.getElementById(‘theValue’);
var num = (document.getElementById(‘theValue’).value -1)+ 2;
numi.value = num;
var newdiv = document.createElement(‘div’);
var divIdName = “my”+num+”Div”;
newdiv.setAttribute(“id”,divIdName);
newdiv.innerHTML = “”;
ni.appendChild(newdiv);
so do I need to put setTimeout(“myBar.loaded(‘jsfile1.js’)”, 500); at the end of that code or beginning?.
Thanks
Very good tutorial.But what about the other type of file like css, images, page text, etc…
Very nice Script!
We use it on http://www.nehemedia.de to preload a bunch of large images before displaying them.
Therefore I added some functions (addImage(); imageLoaded(); and so on..) to your script.
It still needs some enhancements but works just fine right now You helped me a lot by this script! Thanks!
Greetings from Germany