...

View Full Version : How to combine Javscripts into one JS



cryoffalcon
03-27-2012, 05:55 PM
Hi,
well i have heard alot about combining script but never did that as i always had doubts about the proper method of doing it, as these days following standards matters alot for SEO.
I want to combine scripts together into one file, lets take an example i will provide 3 scripts

1-

<script type='text/javascript'>
$(document).ready(function () {
// find the elements to be eased and hook the hover event
$(&#39;div.jimgMenu ul li a&#39;).hover(function() {
// if the element is currently being animated
if ($(this).is(&#39;:animated&#39;)) {
$(this).addClass(&quot;active&quot;).stop().animate({width: &quot;310px&quot;}, {duration: 450, easing: &quot;easeOutQuad&quot;, complete: &quot;callback&quot;});
} else {
// ease in quickly
$(this).addClass(&quot;active&quot;).stop().animate({width: &quot;310px&quot;}, {duration: 400, easing: &quot;easeOutQuad&quot;, complete: &quot;callback&quot;});
}
}, function () {
// on hovering out, ease the element out
if ($(this).is(&#39;:animated&#39;)) {
$(this).removeClass(&quot;active&quot;).stop().animate({width: &quot;83.7px&quot;}, {duration: 400, easing: &quot;easeInOutQuad&quot;, complete: &quot;callback&quot;})
} else {
// ease out slowly
$(this).removeClass(&quot;active&quot;).stop(&#39;:animated&#39;).animate({width: &quot;83.7px&quot;}, {duration: 450, easing: &quot;easeInOutQuad&quot;, complete: &quot;callback&quot;});
}
});
});
</script>

2-

&lt;script type=&quot;text/javascript&quot;&gt;
(function($) {
$.fn.sorted = function(customOptions) {
var options = {
reversed: false,
by: function(a) {
return a.text();
}
};
$.extend(options, customOptions);

$data = $(this);
arr = $data.get();
arr.sort(function(a, b) {

var valA = options.by($(a));
var valB = options.by($(b));
if (options.reversed) {
return (valA &lt; valB) ? 1 : (valA &gt; valB) ? -1 : 0;
} else {
return (valA &lt; valB) ? -1 : (valA &gt; valB) ? 1 : 0;
}
});
return $(arr);
};

})(jQuery);

$(function() {

var read_button = function(class_names) {
var r = {
selected: false,
type: 0
};
for (var i=0; i &lt; class_names.length; i++) {
if (class_names[i].indexOf(&#39;selected-&#39;) == 0) {
r.selected = true;
}
if (class_names[i].indexOf(&#39;segment-&#39;) == 0) {
r.segment = class_names[i].split(&#39;-&#39;)[1];
}
};
return r;
};

var determine_sort = function($buttons) {
var $selected = $buttons.parent().filter(&#39;[class*=&quot;selected-&quot;]&#39;);
return $selected.find(&#39;a&#39;).attr(&#39;data-value&#39;);
};

var determine_kind = function($buttons) {
var $selected = $buttons.parent().filter(&#39;[class*=&quot;selected-&quot;]&#39;);
return $selected.find(&#39;a&#39;).attr(&#39;data-value&#39;);
};

var $preferences = {
duration: 800,
easing: &#39;easeInOutQuad&#39;,
adjustHeight: &#39;dynamic&#39;
};

var $list = $(&#39;#data&#39;);
var $data = $list.clone();

var $controls = $(&#39;ul#gamecategories ul&#39;);

$controls.each(function(i) {

var $control = $(this);
var $buttons = $control.find(&#39;a&#39;);

$buttons.bind(&#39;click&#39;, function(e) {

var $button = $(this);
var $button_container = $button.parent();
var button_properties = read_button($button_container.attr(&#39;class&#39;).split(&#39; &#39;));
var selected = button_properties.selected;
var button_segment = button_properties.segment;

if (!selected) {

$buttons.parent().removeClass(&#39;selected-0&#39;).removeClass(&#39;selected-1&#39;).removeClass(&#39;selected-2&#39;);
$button_container.addClass(&#39;selected-&#39; + button_segment);

var sorting_type = determine_sort($controls.eq(1).find(&#39;a&#39;));
var sorting_kind = determine_kind($controls.eq(0).find(&#39;a&#39;));

if (sorting_kind == &#39;all&#39;) {
var $filtered_data = $data.find(&#39;li&#39;);
} else {
var $filtered_data = $data.find(&#39;li.&#39; + sorting_kind);
}

if (sorting_type == &#39;size&#39;) {
var $sorted_data = $filtered_data.sorted({
by: function(v) {
return parseFloat($(v).find(&#39;span&#39;).text());
}
});
} else {
var $sorted_data = $filtered_data.sorted({
by: function(v) {
return $(v).find(&#39;strong&#39;).text().toLowerCase();
}
});
}

$list.quicksand($sorted_data, $preferences, function () { $(this).tooltip (); } );

}

e.preventDefault();
});

});

var high_performance = true;
var $performance_container = $(&#39;#performance-toggle&#39;);
var $original_html = $performance_container.html();

$performance_container.find(&#39;a&#39;).live(&#39;click&#39;, function(e) {
if (high_performance) {
$preferences.useScaling = false;
$performance_container.html(&#39;CSS3 scaling turned off. Try the demo again. &lt;a href=&quot;#toggle&quot;&gt;Reverse&lt;/a&gt;.&#39;);
high_performance = false;
} else {
$preferences.useScaling = true;
$performance_container.html($original_html);
high_performance = true;
}
e.preventDefault();
});
});
&lt;/script&gt;

3-

<script type='text/javascript'>

var _gaq = _gaq || [];
_gaq.push([&#39;_setAccount&#39;, &#39;UA-15016456-1&#39;]);
_gaq.push([&#39;_trackPageview&#39;]);

(function() {
var ga = document.createElement(&#39;script&#39;); ga.type = &#39;text/javascript&#39;; ga.async = true;
ga.src = (&#39;https:&#39; == document.location.protocol ? &#39;https://ssl&#39; : &#39;http://www&#39;) + &#39;.google-analytics.com/ga.js&#39;;
var s = document.getElementsByTagName(&#39;script&#39;)[0]; s.parentNode.insertBefore(ga, s);
})();

</script>

I want to add them to one file and then yes i am going to make it external.
Here i have a few questions:
1- Can any type of scripts be added together?
2- Is there a general rule of doing this combination of scripts (e-g remove the <script> tags from start and end of all then give spaces between each and you are done).
3- Should one use JS compressors? if yes, what are advantages and disadvantages of doing so?

I asked a few question together as i don't want to spam this forum ^_^ anyway these all question are related to my topic :D

blaze4218
03-27-2012, 07:05 PM
1) Any combination of javascripts can be combined into the same file if written properly in the first place.
2) remove the script tags, ensure the order of the scripts doesn't change (if you loaded script1.js, then script2.js- be sure to put them in the same order in your new file). This prevents the breaking of any dependencies.
3) yes.
advantages- should be obvious, the script will load faster. but also, some compressors (like googles closure compiler) will even run optimizations (like caching DOM references that are used often) on your code allowing for faster execution, and removal of unreachable/unused code.
disadvantages- extra testing with more aggressive compilers, to ensure they don't break your code. certain coding practices lead to more advanced compressions that might break other code...


https://developers.google.com/closure/compiler/docs/api-tutorial3

Philip M
03-27-2012, 07:36 PM
Is there in fact any practical advantage in combining multiple scripts into one external file? Run faster - a few milliseconds perhaps.

cryoffalcon
03-27-2012, 08:30 PM
1) Any combination of javascripts can be combined into the same file if written properly in the first place.
2) remove the script tags, ensure the order of the scripts doesn't change (if you loaded script1.js, then script2.js- be sure to put them in the same order in your new file). This prevents the breaking of any dependencies.
3) yes.
advantages- should be obvious, the script will load faster. but also, some compressors (like googles closure compiler) will even run optimizations (like caching DOM references that are used often) on your code allowing for faster execution, and removal of unreachable/unused code.
disadvantages- extra testing with more aggressive compilers, to ensure they don't break your code. certain coding practices lead to more advanced compressions that might break other code...


https://developers.google.com/closure/compiler/docs/api-tutorial3

Well thanks for a detailed reply, it do answer my all questions, just a little bit more. I have scripts without any particular sequence i can place any script above another one (while they are having <script> tags) but when i will be making one file out of them i would put them without any sequence as i don't know if they have sequence or not, what do you think will they work? and do i have to give space after pasting every script?

cryoffalcon
03-27-2012, 08:32 PM
Is there in fact any practical advantage in combining multiple scripts into one external file? Run faster - a few milliseconds perhaps.

What are you talking about, if it was just a few miliseconds why would it be recommended everywhere and by everyone? there must be a good reason for it. As you are my first person who is saying this. I never heard anyone before you.

blaze4218
03-27-2012, 08:54 PM
Philip M is not wrong... in a sterile environment you might only save but a few milliseconds per script,but that is true with each round trip the client makes to the server.
In and edge case over slow internet connections, on slow/old computers(or phones), pulling 300 do-nothing scripts, etc: You could save as much as a second or two.
Combining as many resources as you can into as few files as possible is called a "micro optimization".

Some feel that such micro optimizations are for large web applications like amazon.com or maps.google.com where every transaction between server and client(s) would influence the server load, and that for smaller sites it's a waste of time/money. It's up to you to decide what is best for your needs...

i would put them without any sequence as i don't know if they have sequence or not
my recommendation is the same. If you don't know what dependencies might exist, you are better of using the order in which they are currently loaded into the document.

IF your code is written properly it would require no empty space between scripts
if you can't be sure... by all means, put one line break between scripts.

P.S. don't use a compressor/minifier/compiler on your source code, only on production code. If you don't know the difference: keep a copy of your code on your computer before compressing, and only load the compressed code to your website.

Philip M
03-27-2012, 08:59 PM
Some feel that such micro optimizations are for large web applications like amazon.com or maps.google.com where every transaction between server and client(s) would influence the server load, and that for smaller sites it's a waste of time/money. It's up to you to decide what is best for your needs...


That is what I believe. :) For smaller sites it's a waste of time/money.

blaze4218
03-27-2012, 09:21 PM
I agree. I've never really done anything that was either so big, or had so many users that I have ever needed to concern myself with it. However, I write my code to take advantage of closure-compiler optimizations like variable renaming and results caching, and these are even greater minified when the compiler only has one src to work from... with that, I can usually squeeze all my functionality for all pages on a single site into a 5k-15k single js file that only needs to be downloaded on the landing page, after that, the js file is pulled from the cache. considering my disparate library files can span 60k+, I feel it's worthwhile to do it just as a matter of practice...

but that's really more about the question of using compressors, and I feel that if you are using a compressor anyway... might as well load it all in there at once...

felgall
03-27-2012, 09:28 PM
If you don't know what dependencies might exist, you are better of using the order in which they are currently loaded into the document.

With properly written scripts the only dependencies should be on library JavaScripts that are in many cases available from third party sources that will significantly speed download times where the common copy is used that is possibly already cached on your visitor's computer (eg. jQuery). These libraries therefore should NOT be combined in a single file with your other scripts (where you'd then significantly slow the loading of the page for those who already have a copy of the library cached from the third party source.

Rewriting the JavaScript so that it is as unobtrusive as possible is far more useful in both making the page easier to maintain and reducing the possibility of conflicts than combining them together into once external file is. So ideally all the scripts to be combined will have already been rewritten so that they are completely independent of anything else apart from one (or more for form validation) ids in the page. Combining them into one script is then a simple matter of placing all of the code into one file without regard to the order of the scripts.

Also combining scripts like that is only really useful if they are all mostly used in all the same pages (or at least across pages that your visitors are likely to visit together) since the gain from only downloading one file would be lost if most of the content of the file isn't actually needed by any of the pages your visitor actually visits.

Combining scripts would be one of the very last things you'd look at once you'd optimised everything else.

Lerura
03-27-2012, 09:38 PM
What are you talking about, if it was just a few miliseconds why would it be recommended everywhere and by everyone? there must be a good reason for it. As you are my first person who is saying this. I never heard anyone before you.

If you need all the data un all of the .js files you could save a bit by mergeing them into one file.

But if each document only used a small part of the script, then it will be a waste to merge them.

Imagine you have a .js file of 1.5MB which contains ALL your scripts.
the file contains these three lines:

function sortCriteria(){
return (a<b?1:b<a?-1:0);
}
which the for most of your document, is the only tunction that you use.

can you give me any good reason for loading the whole 1.5MB file for that?
There ain't one!
-----
It is recommended that you merge files if they contains related data.
e.g. if one function always depends on another function.
Then it would be stupid to save these 2 functions into their own seperate files.

But if you have e.g a banner rotator script, and gallery script, that have no common constants function or whatever, and is only sometimes used within the same seesion, then save them into separate files.

And the same for graphics(Sprite Images)
You might have 200 buttons spread over you entire site each with 3 or four states, giving a total of 600-800 sprites. button each page only use 12 sprites, then you could waste a lot of bandwidth and download time.

If users often ends up visiting so many pages that a majority of the sprites is used during the session, then is it mostly recommended that you combine them.

But if you have a site where user mostly only visit 1 or 2 pages, using only a few of the sprites, then the sprites should be split over multiple files.

If splitting or merging files is optimal, depends on many factors:
Number of files used.
Size of the files.
Unused file content.

I have also seen a lot statements, that merging files is always recommended.

But if it means that you might save a few HTTP-requests and a few bytes, then it doesn't matter.

Do your own evaluations on what is best, instead of just listening to recommendation.

blaze4218
03-27-2012, 11:18 PM
With properly written scripts the only dependencies should be on library JavaScripts that are in many cases available from third party sources that will significantly speed download times where the common copy is used that is possibly already cached on your visitor's computer (eg. jQuery). These libraries therefore should NOT be combined in a single file with your other scripts (where you'd then significantly slow the loading of the page for those who already have a copy of the library cached from the third party source.

Rewriting the JavaScript so that it is as unobtrusive as possible is far more useful in both making the page easier to maintain and reducing the possibility of conflicts than combining them together into once external file is. So ideally all the scripts to be combined will have already been rewritten so that they are completely independent of anything else apart from one (or more for form validation) ids in the page. Combining them into one script is then a simple matter of placing all of the code into one file without regard to the order of the scripts.

Also combining scripts like that is only really useful if they are all mostly used in all the same pages (or at least across pages that your visitors are likely to visit together) since the gain from only downloading one file would be lost if most of the content of the file isn't actually needed by any of the pages your visitor actually visits.

Combining scripts would be one of the very last things you'd look at once you'd optimised everything else.
Sometimes I wonder how much headache you could spare yourself if you spent more time reading and addressing actual thread questions and less time trying to pick apart useful contributors only to find an argument where one doesn't usually exist... There were 3 questions put forth (4 if you include the title) and you have answer none of them.

No-one here has suggested (or advocated) combining common libraries with site level scripts. Take a look at post#1, OP would like those 3 scripts combined into 1. I do recall, however, advocating well structured code.

Since I don't expect the OP to wake up tomorrow and code JavaScript at your level, I must assume the possibility that perhaps a variable conflict occurs between 1 or more user generated scripts. And rather than the approach of "be better, or stop coding JavaScript", I considered it more helpful not to provide vague advice that might introduce new errors. "unobtrusive JavaScript" is little more than a buzzword to many without an example to support the claim. So I reiterate
If you don't know what dependencies might exist, you are better of using the order in which they are currently loaded into the document.
and further state: if you would like help finding such possible errors, which would result from poor coding practices, this would be a great place to find that help.

All of which is secondary to using "JS compressors", because if you do choose to use one for your -non library- production code, you will almost always gain greater compression by combining multiple scripts into one, especially if you are novice and make the occasional mistake. Which I will forgive you for even if felgall does not

It's up to you to decide what is best for your needs


Do your own evaluations on what is best, instead of just listening to recommendation.

felgall
03-28-2012, 02:16 AM
't expect the OP to wake up tomorrow and code JavaScript at your level, I must assume the possibility that perhaps a variable conflict occurs between 1 or more user generated scripts.

And the OP is far better off resolving such conflicts and improving the quality of the code in the scripts and forgetting about combining the scripts together.

The savings to be achieved by combining scripts into one file are the writing on top of the icing on top of the cake. Something that someone who is still struggling to actually bake the cake shouldn't even be thinking about yet.

Until the code is very close to perfect there will be far greater benefits to be achieved by adjusting the code itself toward perfection than will ever be achieved by combining files together.

Unless you are a JavaScript expert there's no point in even thinking about any possible benefits to be gained by combining scripts together. You can gain benefits thousands of times larger by making other changes. I know that I have a way to go before any such changes would provide any benefit to the scripts that I write even though the scripts I write now are much cleaner than those I wrote twelve years ago.

cryoffalcon
03-28-2012, 12:29 PM
Well as far as my javascript knowledge is concerned i proudly say i am a newbie but its okay as i was once newbie to css too but now its long gone story, as soon as i find time from my work i will be learning it. ONE THING THAT I WILL NOT AGREE is that if i don't have knowledge of javascript then i shouldn't combine it. Well combining it into one file and then compressing it, gives me advantage of smaller size, fewer http requests and caching ofcourse. And yes i will have the same scripts on every page of my site, no page will be missed, so for me its really good.
And i am glad you people brought your knowledge to discussion it was like sitting and listening to the explanations of E=Mc2, maybe a little more hard ^_^

Scripts are my favorite but they are hard for me without a doubt as i am an accountant who is in love with site developments. Once again thanks to you all for help. Its you guyz who make forum helpful.

Philip M
03-28-2012, 12:40 PM
i am an accountant

Really? Most accountants are literate and know that the personal pronoun I is a capital letter. :)


Until the code is very close to perfect there will be far greater benefits to be achieved by adjusting the code itself toward perfection than will ever be achieved by combining files together.


"The best is the enemy of the good" - Voltaire

tpeck
03-28-2012, 03:37 PM
My tuppence worth...

I don't think it's been mentioned that combining scripts makes it a helluva lot easier to access the contents of same when working on a project with pages that access twenty or so scripts.

I just take care to separate them with comments and give the parts titles (like most people do).

And do you really want to reference a dozen or so scripts in a page header?

As for felgall's comments - I love having all this good stuff on the same page for later reference, so keep it coming...

And I too wish people would stop writing "i' for I (sorry cryoffalcon!), but then I wish we still wore spats and braces. But seriously, I am of the opinion that taking the same care with language is part of the same technique of getting things right with that literal beast javascript. So it should pay dividends to do so.

blaze4218
03-28-2012, 10:56 PM
Unless you are a JavaScript expert there's no point in even thinking about...
I feel almost guilty dragging this thread any further, but I really must address this point.

I too appreciate felgall's candor. I feel that we can all improve through this very discourse, not to mention felgall did present points that should be considered by cryoffalcon (and all others)

But there must be a better way to present such ideas than telling a person that "if your not already the best, you should wait until you are the best before learning something that could improve/further your knowledge"... such comments are both unnecessary and judgmental (not to mention flat out wrong) and have no place here.

There are instances in which new scripters over-reach and try to create a shopping cart checkout, or capture personal information with JavaScript; and by all means, let us thwart such efforts. But experimentation with combining scripts can only serve to aid in ones understanding of how the language actually works, and I for one learned a great deal by dabbling in things I had yet to understand (in a stable environment). So by all means- offer your two cents, and further elaborate on the topic... but do so with useful information. Don't tell people who are just looking for help, or are just trying to be helpful, that they are too inexperienced to do anything useful and they need to go back to the beginning and learn how javascript really works before asking such questions. I don't think anyone here is qualified to assert what anyone else should or should not spend their time studying.

For example- in this particular case we have an accountant who is just looking to give a little boost to his site's performance, and the conversation has steered into what a waste of time that is and how they should be examining the quality of the code and learning javascript, blah blah blah... Why should this person give two squirts about learning javascript??

In the end what I'm really saying is I agree with what felgall says, but take great concern with how it's being said. It's aggressive, judgmental, and counter-productive. I fear it leads newbies astray...

Mishu
03-29-2012, 12:50 AM
There's nothing wrong with combining scripts as long as you take care to handle any potential conflicts.

I always start with one general script file for the website and add to it as required. The main reason I like to have just one js file is that my Netbeans IDE then lists all the functions in the navigation pane in alphabetical order and to go to a function in the js file I just double-click the function in the navigation pane and I then get taken straight to it. No stuffing around scrolling up and down or using the find feature in a js file to look for a function.

My js files are small and so the loading time is unnoticeable for me and so irrelevant.

venegal
03-29-2012, 02:19 AM
A few comments here; I won't quote anyone in order to not make this thread any more inflammatory, but there's a bunch of things that might be relevant to the OP's questions:

a) The original idea behind combining scripts was not just about a minor millisecond optimization. Depending on the user location, the ping to your server can easily be 300ms, and when scripts are loaded sequentially, serving ten separate script files instead of one can make a difference of 3 seconds in loading time, which has a huge impact on user experience (so this isn't really about server load optimization). Browsers are smarter now, of course, but it's still not a bad idea to combine scripts in production.

b) When I say "in production" I mean exactly that: Of course you will want to leave your code neatly seperated into different files for maintenance reasons, but it's a great idea to combine and, for that matter, minify them in your production environment. Clearly that's much too tedious to do manually, but you can easily write a piece of server side code to do that for you, which you can reuse for all your websites.

Some pseudocode might look like that:


if production (probably meaning server name isn't localhost) {
if production script file has a more recent last changed timestamp than all your development script files, do nothing
else combine and minify all your development scripts and write the result to the production script file
output script tag for the production script file
}
else {
output seperate script tags for all the development script files
}


c) On a semantic level, it's impossible to cause any conflicts by combining scripts. If there's a variable conflict or a dependency problem after combining, it has already been there before. On a syntactic level, you can get into trouble if 1.) you're lacking a rigorous use of semicolons and 2.) you don't put a newline between scripts — the interpreter won't know then where the last statement ends. But that's pretty much all you have to worry about.

d) There's almost always more harm than benefit in serving different scripts to different pages. Serving a single script gives you the obvious cache advantage, of course, but it's also noteworthy that the fact that that single combined file will be significantly larger than a specific file you might be serving to a specific page is pretty much irrelevant: With increasing bandwidths, network latency becomes much more relevant than file size. Network latency pretty much comes down to the speed of light, which won't change any time soon, so an additional HTTP request per page will have larger and larger impacts on overall load time as bandwidths increase. With current average bandwidths, this means that serving the same 10k of Javascript to all the pages will be much better for international user experience than serving 10 different 1k files to 10 different pages. (That 1.5m Javascript file mentioned before is absurd, unless you write really crappy code.)

cryoffalcon
03-29-2012, 10:04 AM
[QUOTE=Philip M;1209520]Really? Most accountants are literate and know that the personal pronoun I is a capital letter. :)

Well to make it more accurate Chartered Accountant. And as far as 'i' is concerned you should know we use Excel kind of stuff that corrects the grammar stuff for us, so you can call it a bad habit ^_^

cryoffalcon
03-29-2012, 10:12 AM
And I too wish people would stop writing "i' for I (sorry cryoffalcon!), but then I wish we still wore spats and braces. But seriously, I am of the opinion that taking the same care with language is part of the same technique of getting things right with that literal beast javascript. So it should pay dividends to do so.

Well don't be sorry, its okay i understand. I am not a script writer but i do am CSS writer and i understand the seriousness of writing correct codes. One time i just forgot to place a closing bracket at the end of a class and my whole CSS was bringing really weird results. Until i found that i have mistakenly deleted it while deleting the lower code.
Javascript is my favorite but as its hard so i am scared of it and learning it slowly and i am not going to correct this 'i' just to tease some more fellas :P i am kidding. But what can i do its a bad habit :D

Philip M
03-29-2012, 10:15 AM
In this day and age with 100 applications for each job vacancy, a surefire way to get your cv chucked in the wastebin right away is to reveal literacy problems with poor grammar, poor spelling and/or poor punctuation. :cool: And clients of professional firms dislike receiving reports etc. with "uncorrected grammar stuff". Your bad habit could cost you dear. And you seem to be blissfully unware of the important difference betweeen its and it's.

cryoffalcon
03-29-2012, 10:20 AM
I feel almost guilty dragging this thread any further, but I really must address this point.

I too appreciate felgall's candor. I feel that we can all improve through this very discourse, not to mention felgall did present points that should be considered by cryoffalcon (and all others)

But there must be a better way to present such ideas than telling a person that "if your not already the best, you should wait until you are the best before learning something that could improve/further your knowledge"... such comments are both unnecessary and judgmental (not to mention flat out wrong) and have no place here.

There are instances in which new scripters over-reach and try to create a shopping cart checkout, or capture personal information with JavaScript; and by all means, let us thwart such efforts. But experimentation with combining scripts can only serve to aid in ones understanding of how the language actually works, and I for one learned a great deal by dabbling in things I had yet to understand (in a stable environment). So by all means- offer your two cents, and further elaborate on the topic... but do so with useful information. Don't tell people who are just looking for help, or are just trying to be helpful, that they are too inexperienced to do anything useful and they need to go back to the beginning and learn how javascript really works before asking such questions. I don't think anyone here is qualified to assert what anyone else should or should not spend their time studying.

For example- in this particular case we have an accountant who is just looking to give a little boost to his site's performance, and the conversation has steered into what a waste of time that is and how they should be examining the quality of the code and learning javascript, blah blah blah... Why should this person give two squirts about learning javascript??

In the end what I'm really saying is I agree with what felgall says, but take great concern with how it's being said. It's aggressive, judgmental, and counter-productive. I fear it leads newbies astray...

Well i am really glad what you wrote is what we newbies feel ^_^
It do scares the **** out of a person who already knows that javascript is not like CSS which has a language that close to english :D
Being an accountant (as i am not genius of script writing as you guys) i always follow one philosophy that i need to "learn how to use TV rather than how it was invented or made" in most cases i do know how to handle scripts i am not blind but the reality is i can't write, so if you come up with talks like Variables, strings etc you should know i will not understand a single word :D

Just at the footnote, during my accounting life we were told and guided that always use simple and easy language to convey a message (don't use accounting terminologies) as everyone is not accountant or maybe is but not at your level ^_^

cryoffalcon
03-29-2012, 10:30 AM
In this day and age with 100 applications for each job vacancy, a surefire way to get your cv chucked in the wastebin right away is to reveal literacy problems with poor grammar, poor spelling and/or poor punctuation. :cool: And clients of professional firms dislike receiving reports etc. with "uncorrected grammar stuff". Your bad habit could cost you dear. And you seem to be blissfully unware of the important difference betweeen its and it's.

Well it will hurt your feelings to tell you a few things about me :P when i am chating or taking on internet i don't mind to you atleast instead of at least. Grammar is part of my job, i don't like to use it over internet where we all use Short Hand. If you want to bring out mistakes you can point out we don't make faces in reports or CV like this ^_^

As far as my job is concerned right now i work as Reporting and Admin Officer at Minsitry of Urban Development. I have previously worked for WFP (its part of UN) as Finance Officer other jobs includes working as Finance Manager at Private Limited.
My education includes (Pr-Engineering + ACCA + BSC Hons) i have skills in many computer programs and a few web languages (though i am not smart you computer guys, i know)
And my age is 22 years, my work experience is of almost 4 years (full time).
The reason of saying all this is not to show something i am just saying that i know stuff about interviews, reports etc as i met and have relations with some big people (you can expect me to have a professional behavior) but still at the end i would say, i don't like to stay professional on internet, its boring ^_^

Philip M
03-29-2012, 10:52 AM
And my age is 22 years, my work experience is of almost 4 years (full time).


Wow! As much as almost 4 years! Obviously you are in the happy state of still being young enough to know everything!

What you do is of no consequence to me. But as I say, were it me your cv would not get past the first scanning.



i met and have relations with some big people

Really? :D:D

Mishu
03-29-2012, 10:57 AM
Grammar is part of my job, i don't like to use it over internet where we all use Short Hand. If you want to bring out mistakes you can point out we don't make faces in reports or CV like this ^_^


Totally agree :). The environment like forums like this is totally different to putting together a cv and i don't care less about the relatively common shorthand used in forum posts, social networking posts etc. My only pet hate is the occasional total absence of at least some punctuation which makes some posts a little awkward to read sometime for me.

If I needed to put a cv together I would make sure it was written in the queen's english.

Philip M
03-29-2012, 11:02 AM
If I needed to put a cv together I would make sure it was written in the queen's english.

I doubt it. The Queen's Strine possibly. :D

Shorthand is by no means the same thing as poor grammar, poor spelling and/or poor punctuation.

cryoffalcon
03-29-2012, 11:18 AM
I doubt it. The Queen's Strine possibly. :D

Shorthand is by no means the same thing as poor grammar, poor spelling and/or poor punctuation.

Well i don't know but i think you are a very strict person Philip :D
and as far as my 'big people' thing is concerned i mentioned it just to show that i know how to behave professionally when i am talking to Ministers at a meeting (personal or work reasons). It was not that i am a hot shot. I know my CV will not go through first scanning if its like that but do you expect me to do that ^_^
I know you follow the philosophy "don't say i am professional but also look like one" i don't look like one but i told i am and more important thing here is we all behave here as geeks, we don't follow rules or stuff but we like to create some that's what i guess Programming is.
I don't want to waste time on english rather on scripting (when i am doing the thing that makes me relax done after work, Coding or Developing) I always say "By profession i am a chartered accountant but by passion i am a developer"
In the end i would say you are "Totally Right" about what you are saying but its just that i want to live free on internet and there are few guys 'crazy' like me.

tpeck
03-29-2012, 12:24 PM
I don't think it's possible to cherry-pick your way through accuracy in your life as a developer. You either strive to be a careful person or you don't. Eventually you pay for what you don't do or choose to do poorly and get left behind by those with higher standards. It's a tough world out there.

Since contributors to this forum strive to help each other, it's the least we can do to point this out. No-one minds a slip or two, but deliberate inaccuracy is self-defeating. Many contributors will pass on a poorly written thread. And that will cost you time and eventually money. It's the same in every profession. Those who take care go places. Hollywood has done us all a great disservice by having the mumblers and short-cut takers succeed so often. In real life they just lose.

Sermon over. Have a nice life.

Mishu
03-29-2012, 01:12 PM
Eventually you pay for what you don't do or choose to do poorly and get left behind by those with higher standards.

In forums like this when talking about grammar blah blah I think before judging anyone on their ability to write good english, whether english is someone's native language or not shouild be taken into consideration.

What is also important is to know what is poor english and what is good because then you can use either where it is acceptable. In forums and social networking environments poor english is accpetable to me as long as the message is clear, although sometimes it won't be.

If writing cv's reports, articles blah blah then obviously poor english isnt acceptable and so you can't get away with it like you can in social networking and forums.

tpeck
03-29-2012, 01:22 PM
You're missing the point, sorry. One's first language is irrelevant if you know to do something but choose not to.

Mishu
03-29-2012, 01:28 PM
One's first language is irrelevant if you know to do something but choose not to.

That i agree with totally but unless i am misunderstanding something, some members in these forums are being attacked or mocked because of the poor english in their posts when english is probably not even their native language. That is part of the general context behind what I was saying.

cryoffalcon
03-29-2012, 01:52 PM
Until its internet i will not give value to grammar or spelling mistakes. Target is always to convey the message and i think i do it well so, i am happy ^_^
And to which country i belong or from where i am talking right now, you will not believe if i tell you :D

tpeck
03-29-2012, 01:56 PM
Mishu, is it the lack of language or care that is the issue here? Think about it because this is a javascript programming forum where being punctilious is de rigueur. Without the English language you can build an IT empire; without attention to detail you are sunk.

I don't think anyone here is mocking another's lack of language at all, but one gets quickly tired of a lack of consideration for the viewers having to wade through punctuation salad when we should all be taking pains to be as painstaking as we can.

<Until its internet i will not give value to grammar or spelling mistakes.> Well then, you are the man.

Anyway I've said all I have to say and it's goodnight from me.

cryoffalcon
03-29-2012, 01:59 PM
Well as its a hot topic now going on here and we have lots of smart people around, can someone reply to my this post, as it is having zero replies
here is the link
http://www.codingforums.com/showthread.php?p=1209190#post1209190

Mishu
03-29-2012, 02:03 PM
but one gets quickly tired of a lack of consideration for the viewers having to wade through punctuation salad when we should all be taking pains to be as painstaking as we can.


ok then I have missed something because i am not forced to read anything that is below my tolerance threshold, which is pretty low btw, regarding standard of english. So in public forums like this i don't take much care, if any, on the standard of english as long as i am satisfied my message is still clear.

but when writing reports, articles or anything important to me then i make sure my grammar is correct, i run a spell check and i make sure all the i's are dotted and the t's are crossed.

cryoffalcon
03-29-2012, 02:05 PM
Mishu, is it the lack of language or care that is the issue here? Think about it because this is a javascript programming forum where being punctilious is de rigueur. Without the English language you can build an IT empire; without attention to detail you are sunk.

I don't think anyone here is mocking another's lack of language at all, but one gets quickly tired of a lack of consideration for the viewers having to wade through punctuation salad when we should all be taking pains to be as painstaking as we can.

<Until its internet i will not give value to grammar or spelling mistakes.> Well then, you are the man.

Anyway I've said all I have to say and it's goodnight from me.

Yes you have said a lot, a good night to you. But still i would say it again, until its not coding or professional meeting stuff no one cares for English grammar mistakes, taking care of grammar while you are chating to your friends is hilarious to me. I wouldn't think for a second while sending messages and send it away like this hwr u xD? instead of How are you? as that's how the whole world is today, if you are complaining about not using proper english at forums then you are Wrong, if its script writing or coding stuff then i would agree to you. If you think i am telling you wrong, go to a chat room today and talk in proper english and see how people over there will make fun of you ^_^ you can try http://www.chatango.com for starters :P

cryoffalcon
03-29-2012, 02:08 PM
ok then I have missed something because i am not forced to read anything that is below my tolerance threshold, which is pretty low btw, regarding standard of english. So in public forums like this i don't take much care, if any, on the standard of english as long as i am satisfied my message is still clear.

but when writing reports, articles or anything important to me then i make sure my grammar is correct, i run a spell check and i make sure all the i's are dotted and the t's are crossed.

Mishu you are not missing anything ^_^ its just that some old coders are angry at us (i know its their right, as i am newbie :D and old doesn't include age just means Experienced)
You just used 'btw' in the above comment, now i will complain about it hehehehehehehehee :P

blaze4218
03-29-2012, 03:33 PM
Well thanks for a detailed reply, it do answer my all questions Your own words belie the intent of your later posts... If I had been less than careful in my wording I would suffer my usual barrage of corrections from Phillip M and Old Pedant. This is not done because they are angry at me for my lack of experience, but rather to help me improve. Not to mention the questions you post today will be read by many over time as they google the same questions you have asked, and even if we understand you, their lack of English proficiency might have them struggling with your grammar. No-one here has (that I've seen) ever attacked a poster for grammar or word usage when English was so obviously not their first language. English isn't even a requirement for this forum... I have seen posts in other languages that were answered in both English and the posted language.

Also I will thank you not to compare codingforums to online chat... I am inclined to make up my own acronyms and abrievz as I see fit in while texting or in a chat room, or event using a comment page. But the contributors on codingforums are in fact seasoned professionals taking time out of their busy day to share their knowledge with you. They put time, thought, and (sometimes) effort into addressing your every question. If you don't respect the internet, please at least respect that I will re-read each answer I submit to one of your posts at least 3 times to ensure that I have properly communicated my intent as well as addressed all of your concerns of which I am knowledgeable.

More than a "chat room" this site is intended to be a community of professionals, which is the only reason I ever take the time to address posters that might intimidate new coders. I would prefer to foster a helpful environment for future coders, as it has always been one for me.

Also, it occurs to me that you are only slightly inclined to javascript... did you know that as an accountant and user of excel you are able to greatly enhance the usability and feature-set of all Microsoft products (from custom WMP GUI's to crazy advanced excel macros) with javascript? I recently trained an accountant on some rudimentary JScript to enhance the macros in her already very complex excel worksheets. She now has a much higher paying job...(Yeah, I just too credit for her success :cool: )

VIPStephan
03-29-2012, 04:07 PM
OK, enough said now. Stop the off-topic discussion or the thread will be closed.

Lerura
03-29-2012, 10:25 PM
Back to topic!

Merging .js file is in most cases beneficial, though it rarely makes a noticable difference.

If you always use the scripts together, then it you would save some coding and http-requests if you merge the scripts in order, into one file.

There are cases, where it will cause problems:
e.g.
danishnumbers.js:
UsedLang = 'danish';
numberNames=['nul','en','to','tre','fire','fem','seks',' syv','otte','ni','ti'];
germannumbers.js:
UsedLang = 'german';
numberNames=['null','eins','zwei','drei','vier','fünf','sechs','sieben','acht','neun','zehn'];
translation.js:
Number=prompt('enter a number (1-10) and get its literal name in '+UsedLang);
alert('In '+UsedLang', the literal name for "'+Number+'", is "'+numberNames[parseInt(Number)]+'"');
used either as:

<script src="danishnumbers.js"></script>
<script src="translation.js"></script>
or
<script src="germannumbers.js"></script>
<script src="translation.js"></script>

As both language files are using the same variable names, only with different values, you can't just merge any of the files.

If you merge the language files, then the last assigment would always overwrite the first.

If you merge the german file with the translation file. you can't use the assignments of the danish file.

Then you can only combine them as:

<script src="danishnumbers.js"></script>
<script src="germannumbers_translation.js"></script>
where the german numbers would overwrite the danish numbers.
or
<script src="germannumbers_translation.js"></script>
<script src="danishnumber.js"></script>
where the danish values is are assigned after they are needed.
-----
In such casse, you will have to edit the files before you merge them. e.g.

UsedLangDK= 'danish';
numberNamesDK=['nul','en','to','tre','fire','fem','seks',' syv','otte','ni','ti'];
UsedLangDE= 'german';
numberNamesDE='null','eins','twei','drei','vier','fünf','sechs','sieben','acht','neun','zehn'];
Number=prompt('enter a number (1-10) and get its literal name in '+window['UsedLang'+Lang]);
alert('In '+window['UsedLang'+Lang]+', the literal name for "'+Number+'", is "'+window['numberNames'+Lang][parseInt(Number)]+'"');
and use it as:

Lang='DK';
<script src="allfiles.js"></script>or
Lang='DE';
<script src="allfiles.js"></script>

You then have less http-requests, but the script have become larger.
And then comes the question: is it worth the effort?

tpeck
03-30-2012, 12:16 PM
I don't understand why people care so much about the minuscule time increases or decreases involved these days...

6 month intervals change the entire world in IT. Or am I mad?

Surely, this is all nonsense...

If you have a great many .js scripts - put them into a single script and congratulate yourself (with obvious attention to making the script work).

Please... if you don't want to do it, and have dozens of scripts in your header, who really cares but you?

Lerura
03-30-2012, 10:16 PM
Your are absolutely right tpeck!

The few second that you can save by merging script or making the script few lines shorter is mostly not worth the time.

I have seen many pages where the WM clearly have use time on decreasing the size of their scripts and markup and other low gain optimizations, but are using flash or bmp for a still banners and pictures. :confused:

They should focus on the optimization that really matter.

felgall
03-30-2012, 10:29 PM
There are cases, where it will cause problems:
e.g.
danishnumbers.js:
UsedLang = 'danish';
numberNames=['nul','en','to','tre','fire','fem','seks',' syv','otte','ni','ti'];
germannumbers.js:
UsedLang = 'german';
numberNames=['null','eins','zwei','drei','vier','fünf','sechs','sieben','acht','neun','zehn'];


Provided the JavaScript is written properly ands so has no global variables whatsoever those two pieces of code would be inside different functions and so combining them would not be an issue.

Anyway of the code works with the code in two separate files attached to the bottom of the same page then it will work the same if you simply copy one file into the end of the other and remove the second script tag - regardless of what the files contain.

The biggest benefits are usually to be obtained where you have two scripts that run on different pages that have common code. By splitting out the common code into a separate file and loading two scripts in each page instead of one you gain the benefit of your visitors only having to download the common code once. As this saving will probably be thousands of times greater than the saving from having one file instead of two Splitting the script into multiple files will speed things up unless you have thousands of visitors who only visit one of the pages for every visitor who visits both. Even if that does apply the visitor who visits both would be the more valuable visitor and making their second page load way slower in order to speed up all the first page loads by a miniscule fraction of a microsecond is probably not a good idea.

Splitting JavaScript into multiple files is often beneficial.
Getting ALL the JavaScript out of the HTML into a separate file is always beneficial.
Replacing event handlers with event listeners is usually beneficial.
Wrapping entire scripts in anonymous functions to avoid interference between scripts is always beneficial.
The gains you get from merging JavaScript files into one compared to the benefits you get from the above is a the width of your smallest finger compared to the distance between the Earth and the Sun - ie. Something that 100% of your visitors will not even notice - particularly those on slow dialup).

Mishu
03-30-2012, 11:32 PM
Provided the JavaScript is written properly ands so has no global variables whatsoever those two pieces of code would be inside different functions and so combining them would not be an issue.


There is nothing wrong with using global variables when they are used appropriately and properly



The gains you get from merging JavaScript files into one compared to the benefits you get from the above is a the width of your smallest finger compared to the distance between the Earth and the Sun - ie. Something that 100% of your visitors will not even notice - particularly those on slow dialup).

Until someone actually quantifies "the gains" so apples can be compared with apples and not oranges, then the same gains can be said to be got by splitting js files.

felgall
03-31-2012, 01:57 AM
There is nothing wrong with using global variables when they are used appropriately and properly

Yes there is - the script will break as soon as you add a second script to the page that uses the same global variable for a different purpose.

JavaScript experts consider the mere fact that JavaScript even supports global variables to be one of the worst parts of JavaScript.

Mishu
03-31-2012, 02:03 AM
Yes there is - the script will break as soon as you add a second script to the page that uses the same global variable for a different purpose.


yes that's true but then you haven't used them appropriately or properly like I said. Earlier I posted you need to handle conflicts when combining scripts.
There's nothing wrong with combining scripts as long as you take care to handle any potential conflicts.




JavaScript experts consider the mere fact that JavaScript even supports global variables to be one of the worst parts of JavaScript.

But what is the point you are making? because an obvious reply is so what? because yes some will consider it the worst parts of javascript and other experts will not. So it's a stalemate.

felgall
03-31-2012, 02:35 AM
yes that's true but then you haven't used them appropriately or properly like I said. Earlier I posted you need to handle conflicts when combining scripts.

There shouldn't be any conflicts between properly written scripts even before you consider using both on the same page.


But what is the point you are making? because an obvious reply is so what? because yes some will consider it the worst parts of javascript and other experts will not. So it's a stalemate.

No - because all the experts agree. That's why strict mode disallows a lot of the bad parts of JavaScript and makes it a lot harder to actually define global variables in the first place. It is also why any framework script that you use that was written by an expert will have only the one global variable to use to reference that framework (although jQuery does provide the option of enabling a second shorter global variable to reference it with if other conflicting frameworks are not being used).

Consider the following script for creating a calendar in the web page where the only global entry it uses is the id="cal" in the HTML that identifies the spot where the calendar is to appear. This is as much as ANY script needs to have globally with the exception of frameworks where you would have one global JavaScript variable instead and wouldn't need any id references. Any more than one global reference in any JavaScript indicates that it is a a poorly written script and that the person is at best somewhere on the way from a beginner to an intermediate level.


(function() {
"use strict";
var tabl, row, i, j, r, dow, mth, d, n, w, e, x;
d = new Date();
e = new Date(d.getFullYear(), d.getMonth()+1,0);
x = e.getDate();
w = 1;
n = (36+d.getDay()-d.getDate())%7;
r = 1+((n+x)/7);
dow = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
mth = ['January','February','March','April','May','June','July', 'August','September','October','November','December'];
tabl = document.createElement('table');
tabl.createCaption();
tabl.caption.innerHTML = mth[d.getMonth()]+' '+d.getFullYear();
tabl.createTHead();
row = tabl.tHead.insertRow(-1);
for (i=0; i < 7; i++) {
row.insertCell(i);
row.cells[i].innerHTML = dow[i];
}
tabl.appendChild(document.createElement('tbody'));
for (j=1; j < r; j++) {
row = tabl.tBodies[0].insertRow(-1);
for (i=0; i < 7; i++) {
row.insertCell(i);
if (w < n+1 || w-n > x)
row.cells[i].innerHTML = '&nbsp;';
else row.cells[i].innerHTML = w-n;
if (d.getDate()===w-n)
row.cells[i].className='today';
w++;
}
}
document.getElementById('cal').appendChild(tabl);
})();

Of course many of the scripts that you see on the web were written for Netscape 4 and earlier. JavaScript is so different now to what it was then that it is effectively a completely different language. All those prehistoric JavaScript really need to be completely rewritten to work properly in the unobtrusive fashion that any properly written modern JavaScript uses as a first step. Even a JavaScript beginner would be able to apply most of the necessary changes to do that (assuming they have learnt modern JavaScript instead of taking a history class on how to write JavaScript for Netscape 2).

Mishu
03-31-2012, 02:49 AM
There shouldn't be any conflicts between properly written scripts even before you consider using both on the same page.


That's true but in some cases, depending on the skill level of whoever wrote the scripts in the first place, there might be and that is why I said potential conflicts need to be handled when combining scripts.
There's nothing wrong with combining scripts as long as you take care to handle any potential conflicts.



because all the experts agree.

I don't have any reason to believe that is true.

felgall
03-31-2012, 03:10 AM
That's true but in some cases, depending on the skill level of whoever wrote the scripts in the first place, there might be and that is why I said potential conflicts need to be handled when combining scripts.

That's why I originally suggested that fixing the scripts is a far more worthwhile task to make the scripts run better will achieve greater efficiency gains than will trying to combine poorly written scripts together. Only once the scripts are written properly will the gain from combining two scripts come even remotely close to the gain that can be achieved by recoding the scripts. Combining badly written scripts is a waste of time that could be better spent on improving the scripts.


I don't have any reason to believe that is true.

Have you even looked at the differences that strict mode introduced into what is and isn't allowed in JavaScript when you use it?

If you were to delete any of the variable names from the var list in that example script I posted in an attempt to make that variable global then the script would cease to work as strict JavaScript requires that all variables be defined before they can be used. You would need to explicitly define the variable in global scope in order to make a global variable in strict JavaScript. That does away with all the variables ending up in global scope simply because the person writing the script doesn't define them in the appropriate scope first.

Also strict mode defined inside a function only applies to that function but if you define strict mode globally then ALL the scripts you attach to the page need to be strict JavaScript in order for them to work. So combining badly written scripts into a page that uses strict JavaScript wouldn't work unless the badly written scripts were completely rewritten properly first. At least if they were wrapped inside a function they could continue to run even though they were badly written but any global exposure would be subjected to the new strict rules.

In what way do you disagree that the new strict mode that JavaScript now has (due to the experts asking to have some of the bad parts turned off) indicates a disagreement as to what is and isn't appropriate to use?

There is no reason for any JavaScript to not be able to be written ti use strict mode as that will make it easier to maintain and far less likely to have conflicts with other code. Strict mode has been specifically implemented in a way that ensures that scripts that work in strict mode will work in browsers that don't understand strict mode simply to make it easier to switch to using it now rather than waiting for all the browsers to update to support it. You just need to make sure that you test in at least one browser that does support strict mode so as to make sure that the script will actually run on browsers that support strict mode. If the script doesn't run there then you have made a stupid mistake such as forgetting to define a variable (which without strict mode would have created a global variable that could easily cause a crash when you try to combine the script with others at a later date).

Mishu
03-31-2012, 03:17 AM
In what way do you disagree

You made a statement saying


No - because all the experts agree.

and I replied


I don't have any reason to believe that is true.

If you want me to believe your statement, is it not then up to you to prove it? Otherwise why do have an issue with me or anyone not taking as gospel whatever they read in a forum post?

felgall
03-31-2012, 03:32 AM
If you want me to believe your statement, is it not then up to you to prove it?

The changes that strict JavaScript implemented into how JavaScript works prove it.

It would be like all the experts deciding to have a room painted yellow and you then asking me to prove that the room is yellow and not green when anyone who isn't colour blind would be able to easily see it for themselves.

Read the ECMAScript 5 standard on how strict mode works and see for yourself - or simply try running code in strict mode and see for yourself what happens.

Mishu
03-31-2012, 03:34 AM
The changes that strict JavaScript implemented into how JavaScript works prove it.


It doesn't prove to me your statement


No - because all the experts agree.

Mishu
03-31-2012, 03:36 AM
It would be like all the experts deciding to have a room painted yellow and you then asking me to prove that the room is yellow and not green when anyone who isn't colour blind would be able to easily see it for themselves.


In this scenario, how would anyone know if some experts actually wanted a different colour.

In the case with html5. I am sure there will be a lot of experts who will say at the end that things in html5 should be different but because the way it will be when it is finally recommended by the w3c you could then say that "all the experts" agree with the html5 "standard", which of course will very likely not be the case.

felgall
03-31-2012, 04:03 AM
It doesn't prove to me your statement

Yes it does - all the JavaScript experts were involved in developing that standard either directly as a part of the committee that defined the standard or indirectly as someone who had written code considered good enough to be built into the new version. That they hadn't been able to agree before is why the ECMAScript 3.1 and ECMAScript 4 proposals were never adopted as those who supported one of those didn't want the other. The ECMAScript 5 standard was the compromise that the experts agreed on for us mere mortals to follow.

The new standard also implements most of the good/bad part definitions recognised by the JavaScript validator at jslint.com (created by expert Douglas Crockford who is also the person responsible for the JSON object being built into JavaScript since he wrote the original JavaScript version on which the built in object is based).

Anyway, I try to follow what the experts agree is good JavaScript since 1. it makes sense and 2. following it may eventually get me to their level. It also means that the JavaScript that I write now is better than 99.999999% of what you see on the web and is getting close to the point where the miniscule saving that can be gained from combining two scripts into one would give a measurable percentage (perhaps as high as 1%) of the gain that could be achieved if I were to try to rewrite the code to be even more efficient than it already is (having in some cases gone so far as to run comparisons of alternate code across multiple browsers in order to work out which runs faster the most often). Had I not followed the experts then I'd still be writing the inefficient antiquated code that all those other web sites use - particularly those where the people have learnt by copying other badly written sites or have attended a JavaScript history course instead of one that teaches how to write it properly (there are lots of people teaching those history classes who would benefit greatly by learning JavaScript as then they could teach how to program in JavaScript rather than teaching how to write scripts that were appropriate for Netscape 2).

The biggest gains that can be made with any JavaScript are to rewrite the code to use modern unobtrusive techniques that eliminate as far as possible any potential interference from other scripts and make the script itself far easier to maintain and reuse as a result. The next biggest gains come from examining different ways of achieving the same result and then using the variant that runs faster (one of the many general rules for this is to rewrite code to reduce the number of dots in names as each time code containing a dot is run a lookup need to be made that can be avoided if you get rid of the dots - or example with for loops on an array you set the array length to a variable at the start of the loop and test for that - or process the array in reverse order - so as to avoid the lookup to find the length each time around the loop - unless the processing is able to change the length of the array in which case the loopup becomes unavoidable).

Only the experts write good enough JavaScript for combining scripts into one file to make a big enough difference in the time it takes to do that change than the alternative saving they could achieve by spending the same amount of time on rewriting the poorer parts of their code.

Mishu
03-31-2012, 04:09 AM
Yes it does -

No it does not, so we'll have to agree to disagree on this one :)

felgall
03-31-2012, 04:13 AM
No it does not, so we'll have to agree to disagree on this one :)

That's fine with me. It doesn't hurt me in any way if you write antiquated JavaScript. I'll just continue to teach those prepared to listen how to write JavaScript properly using the latest coding techniques as I have been doing both in the classroom and via the web for the last twelve years.

As for your saying that I haven't proved that all the experts agree that global variables are a bad part of JavaScript - well I haven't come across anyone who knows how to write JavaScript even at an intermediate level who disagrees so I would consider it extremely unlikely that any of the experts disagree with what is obvious to anyone who has reached an intermediate level of ability with JavaScript.

Perhaps the part that is most confusing is that so much JavaScript today is written by people who still haven't got to beginner level.

Mishu
03-31-2012, 04:25 AM
It doesn't hurt me in any way if you write antiquated JavaScript.

That's ok. I don't write antiquated javascript for paying customers.

felgall
03-31-2012, 04:28 AM
That's ok. I don't write antiquated javascript for paying customers.

So all your scripts for paying customers use strict mode.

Mishu
03-31-2012, 04:30 AM
well I haven't come across anyone who knows how to write JavaScript even at an intermediate level who disagrees hso I would consider it extremely unlikely that any of the experts disagree with what is obvious to anyone who has reached an intermediate level of ability wit JavaScript.

And now your backing down by saying the red bit, in contrast to what you said earlier


No - because all the experts agree. So what was all that hoo-ha you posted when I replied to your original statement with


I don't have any reason to believe that is true.The red bit confirms you suspect some might not actually agree and so I am correct in not just blindly accepting what I read in forum posts.

felgall
03-31-2012, 04:40 AM
And now your backing down by saying the red bit, in contrast to what you said earlier

So what was all that hoo-ha you posted when I replied to your original statement with

The red bit confirms you suspect some might not actually agree and so I am correct in not just blindly accepting what I read in forum posts.

No - since I have never met anyone who knows even intermediate level JavaScript who doesn't agree the chances of there being an expert who disagrees is far lower than the likelihood that the universe ended yesterday. If they don't agree then it is far more likely that they are at best a beginner rather than being an expert since not agreeing with the basics upon which all the experts agree is strong evidence that they are not an expert.

That all the experts agree is something that is as close to being certain as anything can be that can't be proved. Also I obviously mean current experts - those who were experts in 2004 who haven't kept up to date with all the changes to JavaScript since then are not even JavaScript beginners today.

Mishu
03-31-2012, 04:45 AM
That all the experts agree is something that is as close to being certain as anything can be that can't be proved.

You're still backing down from


No - because all the experts agree. by now putting conditions on your original statement.

All I said originally in reply was


I don't have any reason to believe that is true. and with all the hoo-ha after that, you still haven't proven to me to reasonable doubt let alone total doubt that your statement is true and now you're putting conditions on your statement.

so fwiw I still don't believe your statement is true and if you have an issue with that then so be it :)

And the fact that you are now backing down on what you said, for me casts doubt on the accuracy of everything else you have posted. But I'm not going to waste my time attempting to verify whether anything else you posted is true or not because it means zip to me personally and is therefore moot.

felgall
03-31-2012, 05:51 AM
And the fact that you are now backing down on what you said

I am not backing down on what I said. In fact as I have been considering it I have been going the other direction. So I'll change my statement one last time to:

No intermediate level (or better) JavaScript programmer would write a script that uses global variables except where absolutely necessary for communicating between scripts. At the very least they would wrap their code inside an anonymous function and only leave what they considered to be necessary exposed. Those more experienced would usually limit any global exposure to as few ids as possible or a single global object.

Anyone who doesn't do that is at best a JavaScript beginner. It is after all fairly trivial for a beginner to learn how to write their JavaScript that way and so avoid 99.9% of the problems that could otherwise occur when moving a script to a different page or incorporating it into a page with other scripts.

It is something really simple and obvious for an intermediate JavaScript programmer to do, just as it is obvious that most scripts should be attached to the bottom of the web page - both so they don't slow down the loading of the page and also so they can run at the earliest moment at which the ids they need to reference exist.

These things make such huge improvements in the maintainability of scripts for such little effort that they are the obvious things to teach first to those at a beginner level wanting to learn more.

All the experts agree because anyone who doesn't agree is by definition a beginner or bystander.

Mishu
03-31-2012, 06:07 AM
All the experts agree because anyone who doesn't agree is by definition a beginner or bystander.

I have no reason to believe that is true.


I am not backing down on what I said.

I believe you are backing down for the reasons I posted before, so if you don't agree then so be it :)

venegal
03-31-2012, 04:49 PM
Please keep this thread on topic, which is "advantages/disadvantages of merging/minifying scripts".

Discussing the meta question whether "experts agree" that global variables are bad is a bit useless and won't help anyone. If you absolutely have to, discuss the actual question whether global variables are bad — I suppose that's going to be a rather short discussion, though.

Lerura
03-31-2012, 09:24 PM
Provided the JavaScript is written properly ands so has no global variables whatsoever those two pieces of code would be inside different functions and so combining them would not be an issue.


I cant figure out if you have misunderstood me, or if you are using my code as an example.

I am talking about you having two different database files, that use the same variable names, only have different values.
It could be a gallery script, that you combine with different database files, depending on which gallery you want to show.

Then you can't just merge the database files as is.
You will then have to modify the files so they can merge.

In example: the content of danishnumbers.js and germannumbers.js can't just be merged into:
UsedLang = 'danish';
numberNames=['nul','en','to','tre','fire','fem','seks',' syv','otte','ni','ti'];
UsedLang = 'german';
numberNames=['null','eins','zwei','drei','vier','fünf','sechs','sieben','acht','neun','zehn'];


If the files have no common function or variable names, there is no problem in merging them as is.
But just a single common name would require modification first.

felgall
03-31-2012, 10:44 PM
I cant figure out if you have misunderstood me, or if you are using my code as an example.

Those scripts look like the setup where you are either going to load a different set of language definitions for different pages or where you intend to dynamically swap which script containing the language definitions is attached on a language change request. Combining scripts together in that situation would be completely inappropriate as separate scripts is a part of the functionality and combining them would break the functionality completely.

So I was assuming that you were using that as example content with scripts using the same variables. Now obviously if two scripts use the same variable and expect different values those scripts can't both be used on the same page. The two scripts would not work if both attached to the same page even with them in separate files. So the two scripts would need to be attached to different pages in order for both to work.

So if the all the scripts for the one page were combined together into one file then that page would load a fraction of a millisecond faster through not having to lookup so many files. If the same person then requested the second page that page would load a second or two slower due to having to download the entire script for that second page instead of already having most of it caches (as would apply if each page requested two scripts - one with the common part and one with the part specific to that page).

If we now step back from combining actual JavaScript files together - which usually results in slower loading pages rather than speeding things up - and consider the situation with adding a second script to a page that already has a script attached. In this instance provided that each script has been properly written using modern unobtrusive code there should be almost no possibility of conflicts unless the two scripts actually conflict in what they are trying to do (such as one script that scrolls a specified element down the screen and the second you are trying to add which is supposed to scroll that same element up the screen).

If two scripts that are supposed to interact with the page in ways that don't conflict in the actions they are supposed to perform stop working when both are added to the same page then it indicates that one or both scripts have not been written properly in the first place and the scripts need to be rewritten to reduce their global footprint to a minimum - for example the multiple language script would require one object that can be passed into the main script in order to pass all of the content for that language between the two files. If a conflict still exists in that situation then you would need to make two small additional changes in order to change the name of one of the conflicting objects in the script where it is created and secondly to change the name of that object at the spot where the second script references that object.

The one further way that you might consider combining scripts together would be for example where you have two scripts that provide the same functionality but for two different languages. The way you would combine those scripts would be to identify all of the code that is common between those two scripts and extract that into a common function. The parts that are different would be moved to separate files so that each can be attached to the page that needs it. That would give the time saving on loading the second page that I mentioned earlier. Now if one page needed to be able to dynamically switch between the two languages you'd add yet another separate script file to that page that contains the code that does the switching by dynamically swapping the different language scripts in and out of the page (once each had been referenced once they'd be cached so swapping back would take almost no time at all). If all of the pages need this functionality and you know that you will never need a page to load just one language then you could combine the switching code with the rest of the common functions in the same file for a very small time saving and a loss of flexibility - which would require more work if you ever needed to split the code back out at a future date.

Generally making the code more flexible and easier to maintain outweighs any slight efficiency gains that are achieved only by making the code less flexible and harder to maintain.


"advantages/disadvantages of minifying scripts".

There are no disadvantages to minifying scripts. A minified script still contains the same JavaScript but has simply had all of the comments and unnecessary whitespace removed from it to make the overall file size smaller. You can either keep a copy of the original script on your own computer to make modifying the script easier (creating a minified copy again before uploading it) or if you don't have any comments in the code to start with that the minifier would strip out or you have added the comments back after minifying (eg. copyright notice) then you can easily recover the original even if you didn't keep a copy by using a JavaScript formatter.

There are huge disadvantages to using alternative ways that make the script even smaller. For example jQuery used to offer a compressed version of their script that used PACKER to create a JavaScript file a small fraction of the size of the minified version. With older browsers that only supported HTTP 1.0 this packed version would download a lot faster than the minified version would. The additional overhead of then having the script have to unpack itself before being able to run meant that the actual time saving was only a small fraction of the time saved in downloading but there was still savings to be made by doing that. Now that all browsers support HTTP 1.1, all files sent from the server to the browser can be compressed on the server and decompressed by the browser (without requiring any scripts to do so). The minified version of a script can usually be compressed a lot more in this instance than a script that has already been compressed via a script can be. So with HTTP 1.1 the minified version of jQuery downloads faster than the packed version does - making the packed version much slower as even after it has downloaded it then needs more time to unpack itself. That's why jQuery no longer offers that version even though it appears to be a smaller download.

Lerura
04-01-2012, 12:34 AM
Those scripts look like the setup where you are either going to load a different set of language definitions for different pages or where you intend to dynamically swap which script containing the language definitions is attached on a language change request. Combining scripts together in that situation would be completely inappropriate as separate scripts is a part of the functionality and combining them would break the functionality completely.

OP wanted to merge his files, and was sure that it was always a good thing to merge js-files.

I wanted to show that merging isn't always the right thing to do.

In the case of the example it is possible to merge the files, by giving each language set its own variable names, and changing the way they were refered to. Thus changing it from load different definitions to dynamically swap on request

But it might not be that easy to do, and in some cases it would make future editing very cumbersome. And might also result in a huge increase in the combined file size.
Even in my small example, the increase was 96 characters. just to have one less http-request. Really not worth it!

felgall
04-01-2012, 01:17 AM
But it might not be that easy to do, and in some cases it would make future editing very cumbersome. And might also result in a huge increase in the combined file size.
Even in my small example, the increase was 96 characters. just to have one less http-request. Really not worth it!

I agree.

Adding an extra language would be an example of something far simpler using separate files for each compared to the extra complexity of trying to combine them.

The circumstances where combining scripts doesn't result in a huge additional overhead are so rare and the benefit to be gained in those extremely rare situations is so small that even considering it is generally a waste of time better spent on something else.

If you consider that combining scripts together will always result in slowing down the page then you will be right almost all the time - if you were to take that attitude to a million possible scripts that could be combined you would be right with at least 999,999 of them and would have a good chance of being right with the last one as well.

A good general rule is to NOT combine two separate scripts together. Only where the two files contain parts of the same script should you even consider it and then only if one file isn't shared with other scripts.

There were a lot of scripts written before 2005 (or written since using the antiquated version of JavaScript that had to be used before 2005 to support Netscape) that had a head script and a body script. Since 2005 it has been quite practical to rewrite those scripts so that they can have all the code in a single file attached to the bottom of the body of the page. Doing that generally means a major rewrite of the code though from original JavaScript into modern unobtrusive JavaScript and so in most such cases there will be little if any of the original code in the final combined script.

Lerura
04-01-2012, 02:30 AM
If you have several files that contains the exact same same data
e.g.
4 files that each only contains 3 of following assignment:

Right="Opposite Left"
Left="Opposite Right"
Up="Opposite Down"
Down="Opposite Up"

Then it would be beneficial to merge them into one file with 4 assignments.

Saying that if you would be able to remove duplicate functions or constant, that you usually load at the same time, through different files.
Or if it would make the editing a lot easier.
Or anything that would make a huge difference
Do it!

But if the sole purpose is to get less files. - Don't

felgall
04-01-2012, 05:21 AM
I don't think it's been mentioned that combining scripts makes it a helluva lot easier to access the contents of same when working on a project with pages that access twenty or so scripts.

But a lot slower for the pages to load if each page only uses one or two of the scripts (and you would never use more than three or four scripts on any one page at most if you expect people to actually stay on the page for any length of time). Twenty scripts on a page is sure to drive people crazy and if they don't leave the site completely they'd be very likely to disable JavaScript for the site.

Mishu
04-01-2012, 05:27 AM
But a lot slower for the pages to load if each page only uses one or two of the scripts

How long is "a lot slower" and what would the time difference be if all the scripts were used.

Things like "a lot slower" mean zip to me because with the amount of js I write I have never noticed any difference in loading time. So for me, whether the scripts are combined or not makes no noticeable difference at all.

So as far as I am concerned, whether it is worthwhile to combine scripts or not is to some extent also dependent on the amount of js involved and the other content on the page. Sure, in some cases the extra time might be significant for some people, but to me it's not because it is far too small to worry about in my case.

Philip M
04-01-2012, 09:18 AM
How long is "a lot slower" and what would the time difference be if all the scripts were used.

Things like "a lot slower" mean zip to me because with the amount of js I write I have never noticed any difference in loading time. So for me, whether the scripts are combined or not makes no noticeable difference at all.

So as far as I am concerned, whether it is worthwhile to combine scripts or not is to some extent also dependent on the amount of js involved and the other content on the page. Sure, in some cases the extra time might be significant for some people, but to me it's not because it is far too small to worry about in my case.

I have to say that I agree with Mishu. There is a big difference between coding for Amazon's website and the website of a smaller business or a club, which represents my typical customer, and I suspect Mishu's as well.

I do take all felgall's points on board, and agree that generally making the code more flexible and easier to maintain outweighs any slight efficiency gains that are achieved only by making the code less flexible and harder to maintain, but in addition I prefer clarity, simplicity and easy maintenance to technical perfection - especially where no discernable gains for the user are apparant.

For example, using meaningful variable and function names such as username or function checkValues() rather than abc123 or function q() adds more value than scraping off a millisecond or two. I understand that dial-up is now completely obsolete and high-speed broadband is becoming the norm.

cryoffalcon
04-01-2012, 06:13 PM
I understand that dial-up is now completely obsolete and high-speed broadband is becoming the norm


Well I am from Afghanistan and right now talking from it's capital city Kabul. My internet connection speed is 5KB/s it's a DSL of 128kbps share over 7 users. Previously I was in Pakistan I faced the same issues but now that country got some good internet But here in Afghanistan it's still the Dial up Era.
It's not only Afghanistan there are other countries with slow internet, it is one of the reason that I am trying to focus on speed as 2 seconds means too much when it comes to slow internet connection, every second counts.

Philip M
04-01-2012, 06:25 PM
I understand that dial-up is now completely obsolete and high-speed broadband is becoming the norm


Well I am from Afghanistan and right now talking from it's capital city Kabul.

If you had mentioned that at the outset or in your profile it might have influenced the replies you have been given. :)

felgall
04-01-2012, 08:14 PM
I understand that dial-up is now completely obsolete and high-speed broadband is becoming the norm.

Dialup might be obsolete in some countries but I am sure there are a lot of poorer countries where it is still the norm.

Also high-speed broadband is definitely not the norm here in Australia. Here almost everyone is still on mid-band speeds. There is a national rollout of a national broadband service offering bottom of the range broadband speeds but that is expected to take about another six to eight years before it reaches everyone.The new system does have the capability to handle fast broadband speeds at a later date but is currently limited to 100Mb maximum. Most people who don't yet have access to the new broadband are still limited to connection speeds under 5Mb.

Since everyone seems to agree that the savings from restructuring code for efficiency are too small to notice (and I never suggested that they would be noticeable) the very much smaller savings from combining scripts would never be noticed at all - probably not even by those on dialup.

felgall
04-01-2012, 10:31 PM
How long is "a lot slower" and what would the time difference be if all the scripts were used.

By "a lot slower" in this instance we are looking at something that takes a few milliseconds longer to run than the alternatives.

Probably somewhere between 10 and a thousand times slower than than the difference saving that one extra file lookup on the server would make.

It is all relative - everything discussed in this thread is talking about things that would need to be repeated thousands or millions of times in order for the difference to become measurable in seconds.

Also the difference that placing all the scripts in one file makes where all the current pages use all the scripts comes when you later introduce a page that doesn't use all the scripts. If most visitors after that time are just going to visit that new page then they have the overhead of downloading that extra code for the script that page doesn't use. While the overhead is too small for most of them to notice either way (except those still on slow dialup) the amount by which that page is slowed for them will be many times that of the amount by which the other pages (when visited individually) load faster due to the scripts being combined. If you have millions of visitors who visit the new page that doesn't use one of the scripts and only a handful of people that visit the other pages that use all the scripts then splitting that script out so as to not include it in the page that doesn't need it would speed up the page load very slightly (but probably unnoticeably) for those milions of visitors who only visit that one page. The bigger impact would be on the bandwidth that your site saves by not sending millions of copies of a script that never gets run.

Mishu
04-01-2012, 10:31 PM
Since everyone seems to agree that the savings from restructuring code for efficiency are too small to notice ......

That's certainly the case for me. The main advantage for me to have a single javascript file is that all the js is then in one place. My Netbeans IDE lists all the functions and global variables in alphabetical order in the navigation pane and I can quickly go to any function by double clicking it in the nav. pane without having to scroll up and down the file looking for it or a variable and so I don't have to waste time putting them in alphabetical order in the actual file. :)

tpeck
04-02-2012, 12:22 AM
I have heard that hooking your modem up to the router (one that allows it - or a router that dials up) instead of connecting it to the PC improves dialup speeds. Maybe disable javascript altogether?

Lerura
04-02-2012, 01:23 AM
The bigger impact would be on the bandwidth that your site saves by not sending millions of copies of a script that never gets run.
Right!

If you are one of those that have a million visitors every day, every millisecond that you can save in average transfer time, makes a big difference.

Just 1 millisecond per visitor then gives 1000 seconds (~16.6 min.), while 1 second per visitor gives 11,6 days of extra transfer time.

Each simultaneous transfer will of course divide this duration.

Philip M
04-02-2012, 08:10 AM
Right!

If you are one of those that have a million visitors every day, every millisecond that you can save in average transfer time, makes a big difference.

Just 1 millisecond per visitor then gives 1000 seconds (~16.6 min.), while 1 second per visitor gives 11,6 days of extra transfer time.

Each simultaneous transfer will of course divide this duration.

Exactly so! But the sites I am involved with receive perhaps 20-100 visitors a day. Like so many things, it is a case of horses for courses. Once more, I prefer clarity, simplicity (as opposed to gratuitous complication) and easy maintenance to technical perfection - especially where no discernable gains for the user are apparant.

felgall
04-02-2012, 10:02 AM
Once more, I prefer clarity, simplicity (as opposed to gratuitous complication) and easy maintenance to technical perfection - especially where no discernable gains for the user are apparant.

I agree.

My comments about rewriting code to make it more efficient were made with respect to combining scripts into one file. The gain from combining two JavaScript files into one is small compared to even minor code changes to improve efficiency. Also there are lots of not necessarily obvious but easy to follow code changes that always provide bigger efficiency changes than combining two files together would (even ignoring any potential slowing caused by combining two scripts that don't always need to run together).

By using the minor changes to the code that are still easy to read and maintain and getting in the habit of coding them that way all the time you don't lose in maintainability. Then when a project comes along where it makes a difference you gain the efficiency benefit automatically.

That's why modern JavaScript classes often teach that you should code a FOR loop to process an array as:


for(var i = 0, ii = ary.length; i < ii; i++)

instead of


for(var i = 0; i < ary.length; i++)

since that minor change saves needing to check how big the array is each time around the loop and so if you were to run that code a few thousand times for an array with hundreds of entries you'd actually save several seconds in processing time. (a very small additional saving can ve achieved if it doesn't matter which order the array is processed in by having the loop work backwards)

The code is not significantly different between any of these alternatives and so is equally easy to maintain (as long as you remember that setting the length to a variable at the start only works when the loop doesn't change the length of the array).

Another example would be to use the properties and methods of a table element to access the entire HTML table rather than using separate DOM calls for each. You end up with much shorter code that is just as easy to read and which runs a lot faster in most browsers (particularly Opera and IE) and only slightly slower than the alternative in Firefox) - again we're talking fractions of a second for a hundred thousand passes of the table but the resultant code is also easier to read and so more maintainable.

The small changes that make your code more efficient are just as easy to get used to as the small changes that make the code more maintainable by making the code less prone to hard to find errors (such as always using === and !== instead of == and !=, always placing constants first when comparing a variable to a constant, and using strict mode).

Where big changes to the code are required in order to achieve small efficiency gains (and efficiency gains are almost always measured in fractions of a millisecond and you need to set up a test loop over 100,000+ iterations just to get a measurement for comparison) the loss of maintainability is such that you'd definitely need to have one of the top 1000 sites on the web to even consider making such a change and then you'd need additional reasons to make the loss of maintainability worthwhile.

For all of the time on almost all web sites and most of the time for the rest efficiency gains at the cost of maintainability are not worth it whereas efficiency gains that don't cost in maintainability are simply an indication of greater programming experience. You just use the slightly more efficient variant by habit simply because using it consistently makes the code more maintainable than only using it where it would make a significant difference would result in a slight loss of maintainability (since someone might not realise that it is coded differently for a reason and recode it to noticeably slow things down (even if you are the only one writing code for yourself will you remeber why you did it differently from the rest in five years?).

tpeck
04-02-2012, 10:19 AM
"For all of the time on almost all web sites and most of the time for the rest efficiency gains at the cost of maintainability are not worth it whereas efficiency gains that don't cost in maintainability are simply an indication of greater programming experience."

Mmm. But most of us are NEVER going to become as experienced as, say, you have become - and that is where you may be correct, but it doesn't help us mere mortals who just want to get things happening.

In this case, I will opt for joining dozens of functions together in the one script - taking care to make it all work, of course - and not worry about the slight (and I mean mere blink of any eye) page delay, except in....Kabul.

felgall
04-02-2012, 11:05 AM
In this case, I will opt for joining dozens of functions together in the one script - taking care to make it all work, of course - and not worry about the slight (and I mean mere blink of any eye) page delay, except in....Kabul.

I can't see any problem in that.

The OP was asking about merging scripts together in order to gain from having one fewer request for a file being sent to the server and the supposed increase in performance that would provide. All of my arguments have been presented to refute that particular efficiency gain and to present other much larger efficiency gains (some actually big enough to be measured in milliseconds) that can in most cases result from splitting files up or reworking code.

There are plenty of valid reasons for merging two JavaScript files into one but the saving to be made by having one less request sent to the server is not one of them.

I am actually working toward reducing the number of scripts that I have attached to pages on one of my own sites in order to improve the maintainability of the scripts since the resultant loss of efficiency by having to download unnecessary scripts into some pages will be more than made up for by that improvement in the maintainability of the code.

Maintainability should almost always come before efficiency. As you get more experienced you learn how to write more efficient code that is just as maintainable if not more so than the less efficient version you previously wrote.

venegal
04-02-2012, 11:18 AM
The gain from combining two JavaScript files into one is small compared to even minor code changes to improve efficiency.


You're comparing two very different things here — combining scripts is about page load time, which is pretty important to users, whereas code efficiency is about client CPU usage, which for most practical uses is pretty much irrelevant.

As for the page load time, I feel I have to reiterate, since my last post seems to have been generally ignored: The main reasoning behind combining files is that depending on the browser/OS, there's a limit on how many Javascript files will be requested simultaneously (worst case, this limit can be as low as 1). For every file over that limit, the cost of a full server roundtrip can be added to the overall page load time.

If, for instance, you're serving a page with one too many Javascript files (meaning 5 over the concurrent request limit) to some average international user with 150ms roundtrip latency and 10mbit/s bandwidth, this means two things:

1.) The page takes 750ms longer to load, which is very noticeable.

2.) A combined Javascript file could be almost 1mb larger before the impact of that added size exceeds those wasted 750ms.

Bandwidths are constantly increasing, whereas network latencies are fairly constant, as they are already pretty near their physical limit, so the cost of HTTP requests won't become any less relevant to the overall page load time in the future.


Also, as I've already mentioned, that maintainability argument that keeps coming up here is irrelevant. Combining and minifying scripts for production is an automated process that has no impact whatsoever on the maintainability of your dev code.

tpeck
04-02-2012, 11:52 AM
The OP was asking about merging scripts together in order to gain from having one fewer request for a file being sent to the server and the supposed increase in performance that would provide.

Really? At first I thought he just wanted to know how best to go about combining scripts. But it's been an illuminating ride.

I agree with you venegal; yet, maintainability is something that cannot be as easily quantified as page load time savings. Sometimes the end product isn't going to be worth our extra effort.

I still believe that what is easier for the average Joe programmer (me!) is likely to be a collated.js file (such as I use). But I could still be argued out of it if I thought it was doing my visitors a real disservice.

venegal
04-02-2012, 12:00 PM
I agree with you venegal; yet, maintainability is something that cannot be as easily quantified as page load time savings. Sometimes the end product isn't going to be worth our extra effort.


My point is that there is no extra effort or impact on maintainability. The automatic script combining and minifying is supposed to be done in the production environment only — in the development environment you won't even notice.

blaze4218
04-02-2012, 04:56 PM
There are no disadvantages to minifying scripts. A minified script still contains the same JavaScript I want to say this is wrong, but before I do, I should clarify: There is a significant difference between code minifiers and JavaScript "compilers". I have run many code samples through JavaScript compilers and found them to make significant changes to the output code. In fact, they can take code that is mostly good and alter it using the very optimizations that you speak of. They also have a tendency to break code. Googles closure-compiler has several tutorial pages that say just that. Extra precautions are required when using such services. Compilers will also remove code that they think is unused. I have seen code removed that should not be, simply because it was not properly exported. I even started a thread a week or two ago asking for help figuring out why a piece of code I ran through closure-compiler took a local variable and made it global... No-one has been able to answer that yet...

Also, I'm with venegal, there has been much discussion of implementing proper optimizations as a matter of practice. This will improve your overall skill, as well as ensure you don't have extra work making the larger sites more efficient... But the same argument goes for compiling your code. My process is that in my development environment I have all my code clean, and built in a "maintainable" fashion. When I perform updates I modify my code in the development environment, click "Compile" and all my separate scripts are combined with my framework (not recommended for jQuery and other popular frameworks) and I upload. I never modify code on a server, and it's appearance has no bearing on future maintainability...


All of my arguments have been presented to refute that particular efficiency gainMost of your arguments have failed to "refute" that point. Some have, but most have merely reflected your opinion that the gain is meaningless and unimportant, and many (contributers) have reflected that same POV starting with Philip M waaay back on page one...
The gain from combining two JavaScript files into one is small (that, for example, in no way disproves efficiency gain; but rather supports the claim adding commentary to quantify the gain)

99% of JavaScript that I write applies to an entire site. I combine all of that into one script. Some smaller businesses require a gallery (in one form or another), this requires a big chunk of code not used on the other 99% of the pages. I would not combine that with my main script. Especially if my analytics indicate that the gallery has the least traffic... These are the small choices we have to make every day to decide what is best for each individual project.

Back to compilers... Certain optimizations are better left to a compiler. For example, in felgalls earlier comment on "reduc(ing) the number of dots". That is a great optimization that will speed up your code. In terms of code maintenance (and this will vary based on your coding style) removing the dots often makes things harder to read. I don't like the overhead of long method chains, but they help me to remember what code snippets are associated with. So to me- reduction in the number of dots is a statement in support of both combining scripts, and compiling. My development code can maintain readability, and the compiler will remove the dots before I upload. Furthermore, if I combine all relevant code into one file, I see a greater reduction in dots, because I don't have to "export" method names to ensure compatibility.

I cannot support a blanket statement that is either in favor, or against combining scripts. It will vary based on the project.

There is no excuse for not minifying code, or not employing the best coding practices that you know how to. It will require extra work, and can even improve your skills (because you must follow the "proper" coding practices mentioned herein... they almost do the work of a Linter as well...)

felgall
04-02-2012, 08:20 PM
worst case, this limit can be as low as 1

Best case for most browsers is one JavaScript file at a time with nothing else downloading with it - that's why the page will always load everything else faster if the JavaScript files(s) are attached last just before the </body> - You need to use an async parameter on the script tag to be able to download JavaScript with other files and not all browsers understand that (it also indicates that you are not using anything in the script that requires the browser to run the script before moving on to the next file which means definitely no document.write statements).

The time difference between downloading one file and downloading two one after the other is insignificant.

If you are really looking to increase the speed at which the scripts download you'd attach one small script directly to the page and have that dynamically add the script tags for the other scripts into the page - those scripts will then be able to download simultaneously giving you a significant saving in download speed due to having broken up your single JavaScript file into half a dozen or more separate files that can thus download in a fraction of the time by downloading in parallel.

If you want to make the JavaScript download faster break it up into lots of small files and request that they all download simultaneously by using JavaScript to add the script tags to the DOM. The only script directly attached to the page would then look something like this:


addJS = function(nm) {
var s = document.createElement('script');
s.type='text/javascript';
s.src=nm;
document.getElementsByTagName('body')[0].appendChild(s);
}
addJS('script1.js');
addJS('script2.js');
addJS('script3.js');
addJS('script4.js');
addJS('script5.js');

venegal
04-03-2012, 12:35 AM
Best case for most browsers is one JavaScript file at a time with nothing else downloading with it

How is that the best case? That's, as I mentioned, the worst case, and having a look at your browser's network console, you'll see that for modern browsers that's no longer the case (in my Firefox it's 6, which seems to be the general concurrent download limit, regardless of file type).


The time difference between downloading one file and downloading two one after the other is insignificant.

Round trip times are not insignificant — I thought I made that clear with the example in that other post. With increasing bandwidths they are becoming the most significant factor in page load time, which is why CDNs are becoming increasingly popular.



If you want to make the JavaScript download faster break it up into lots of small files and request that they all download simultaneously by using JavaScript to add the script tags to the DOM.


This sounds as if you could download an arbitrary number of files simultaneously, which isn't true — the general concurrent download limit still applies (as mentioned 6 in my Firefox).

Using a modern browser that automatically downloads multiple Javascript files simultaneously, there's obviously no benefit in asynchronous loading, so let's have a look at what happens in an older browser:

For every 6 files, the overall page load time gets hit with the time it takes for a network roundtrip. Let's say you split 200KB of Javascript into 10 20KB files. Assuming an average roundtrip time of 150ms and an average bandwidth of 1MB/s, loading all those files will take 300ms for two roundtrips and 40ms for the actual tansmitting, resulting in a total load time of 340ms.

If you just load a single 200KB Javascript file, it's 350ms, which is about the same.

Since you recommended breaking the file up into lots of small files: If you split those 200KB of Javascript into 20 10KB files, your number will be 640ms, whereas using a single file will still be 350ms; the more files, the worse it gets. Also, the higher the bandwidth, the worse it gets: For my connection, it's 604ms vs 170ms.


I miscalculated the times for simultaneous downloads (it was late and I somehow assumed that with multiple simultaneous connections each one could use the full bandwidth, which is obviously wrong) — the real numbers are even worse: 500ms for 10 files and 800ms for 20 files vs. 350ms for a single file.


If someone still wants to use that outdated asynchronous method, it's probably also worth mentioning that you have to be careful about dependencies, because execution order won't be preserved, and you'll want to implement some DOM ready event, so your scripts won't have to wait for all the images to be loaded.

felgall
04-03-2012, 03:18 AM
How is that the best case? That's, as I mentioned, the worst case, and having a look at your browser's network console, you'll see that for modern browsers that's no longer the case (in my Firefox it's 6, which seems to be the general concurrent download limit, regardless of file type).

JavaScript files are a special case - they can normally only single thread for download unless you specify an async or defer attribute in the script tag and the browser recognises that attribute OR you add the script tags dynamically from JavaScript. There are statements such as document.write that will only work correctly if the script downloads by itself - all other files are made to wait for it to finish. The async attribute has been added to allow you to tell the browser that the script doesn't contain such statements and so can be downloaded alongside other files.


This sounds as if you could download an arbitrary number of files simultaneously, which isn't true — the general concurrent download limit still applies (as mentioned 6 in my Firefox).

No, it gets around the ONE file limit specific to JavaScript where the async attribute isn't supported - the eight file limit most modern browsers apply to other file types (or 6 in the case of your copy of Firefox) still apply.


Using a modern browser that automatically downloads multiple Javascript files simultaneously, there's obviously no benefit in asynchronous loading,

Other than that you can only download one JavaScript file at a time if you don't use either async or defer or loading from JavaScript.




If someone still wants to use that outdated asynchronous method, it's probably also worth mentioning that you have to be careful about dependencies, because execution order won't be preserved, and you'll want to implement some DOM ready event, so your scripts won't have to wait for all the images to be loaded.

It isn't outdated as there are still lots of browsers that don't support the async attribute and so only allow one JavaScript file to download at a time (and will make ALL the other files that haven't downloaded yet wait for the script to finish downloading first.

Those that do support the async or defer attribute will have the same dependency issues because with allowing more than one JavaScript to download at a time or to download alongside other files you have the same issue regarding dependencies regardless of which way you do it.

If browsers were to download JavaScript concurrently with other files then if the script contains any document.write statements the content of those statements could end up being inserted in the wrong spot in the page. That's why you need to clearly identify to the browser before it starts downloading the JavaScript file that it doesn't contain any document.write statements by using either an async or defer attribute so that it doesn't single thread the script download so as to maintain the position needed for any code to be inserted by document.write statements. While modern browsers support these attributes older ones don't but that doesn't really matter since adding the script tags from JavaScript itself is effectively equivalent to specifying async and so more than one JavaScript can then download at the same time or one can download concurrently with other files.

Downloading eight files at a time (or however many a particular browser allows) will always better utilize your available bandwidth than downloading them one at a time.


Modern browsers only download multiple JavaScripts simultaneously if you specify a defer or async attribute on the script tag - without that attribute they revert to single threading the JavaScript just in case there is a document.write statement that requires single threading the script.


If you use document.write statements in your JavaScript then you must single thread that script in order for the information to be added to the correct spot in the page.


Also I think you have your calculation wrong regarding the download time for a 200k script. I did a rough calculation and worked out that if it fully utilised the download bandwidth of my internet connection (which is about 5Mb) then it would take about 430ms for the file to download - so you're out on the download time by a factor of 4 even assuming that the file gets the full bandwidth. In my experience a single file would be lucky if it were able to use a quarter of that and usually a lot less. Typically files that size take about four or five seconds to download to my computer. Were I to request for eight such files to download at the same time they would take about five or six seconds in total.

venegal
04-03-2012, 11:32 AM
JavaScript files are a special case - they can normally only single thread for download unless you specify an async or defer attribute in the script tag and the browser recognises that attribute OR you add the script tags dynamically from JavaScript.


Just have a look at your browser's network tab, will you? All current major browsers except Opera download several Javascript files simultaneously, regardless of any defer or async attributes.



Modern browsers only download multiple JavaScripts simultaneously if you specify a defer or async attribute on the script tag - without that attribute they revert to single threading the JavaScript just in case there is a document.write statement that requires single threading the script.


You're mixing up two different concepts here: defer and async are about when a piece of Javascript is executed, not when and how it's loaded. The time at which it's being executed obviously has an effect on the rendering timing, but we're talking about how scripts are loaded here, and that's completely at the browser's discretion — and with modern browsers it's multiple scripts at a time.



Downloading eight files at a time (or however many a particular browser allows) will always better utilize your available bandwidth than downloading them one at a time.


That's true, but it's not the point — no one suggested that loading script files one at the time (which modern browsers won't do anyway) makes any sense. The point is that with increasing bandwidths and constant network latencies downloading one single script file is faster than downloading smaller chunks eight at a time.



Also I think you have your calculation wrong regarding the download time for a 200k script. I did a rough calculation and worked out that if it fully utilised the download bandwidth of my internet connection (which is about 5Mb) then it would take about 430ms for the file to download

I specified the assumptions on the network connection I used to calculate those values, and obviously you'll get different values with different assumptions. I think you don't actually understand how to calculate total download time, though, since you're only talking about your bandwidth and not about network latency, which, as I have pointed out several times now, is becoming the most important factor in page load times. That's the whole reason we're talking about reducing the number of HTTP-requests by combining Javascript files.

tpeck
04-03-2012, 12:53 PM
You lot are endlessly readable. I love it! And learning...

But why not provide a few demo pages where you prove what you are asking us all to believe?

It's like listening to a bunch of horsetrainers with stopwatches before the big race.

Why not show us what you believe to be true?

I'm sorry to say this, but having provided dozens of demo pages in my time (which I have for nearly 10 years continued to provide online as links from this website), I think the main protagonists in this argument are a tad lazy just to proffer information without proof.

Javascript can show timings to the nanosecond (?) right?

Are you up for it?

venegal
04-03-2012, 01:38 PM
But why not provide a few demo pages where you prove what you are asking us all to believe?


There isn't much to demo here (Javascript can measure its execution time but not its load time — this has to be done by the browser or external tools). You can just browse to an arbitrary page with the network tab of your browser's dev tools open, though, and see for yourself how script files are being loaded and what amount of time is used for server roundtrips.

tpeck
04-03-2012, 01:51 PM
So we have to provide the demos.

Mmm. Sorry I think Blaze4218 and Philip M. answered the question on page 1 and the rest is just argument. Interesting, but point scoring only.

Philip M
04-03-2012, 01:55 PM
My book which is entitled "The Meaningless Of Nothing" (500pp) will be published soon. :D:D

blaze4218
04-03-2012, 02:06 PM
Interesting, but point scoring only.

But what a fun ride it's been

venegal
04-03-2012, 05:05 PM
So we have to provide the demos.


If you're really interested, yes. Since browsers are smarter now, the days of huge page load improvements by combining scripts or loading them asynchronously are gone, and I'm not out there to convince anyone to use any specific method.

That number game aside, I mainly got involved to correct a few things that were unambiguously wrong; maybe it helps someone to summarize a few points that came up:


A gain in downloading efficiency is a different thing than a gain in code efficiency.

Modern browsers do not insist on downloading only one Javascript file at a time. There's still a limit, though.

The defer and async properties are not about how and when scripts are downloaded, but about when they are executed, and when the page is rendered.

If one method is definitely better than the others in the current browser scope, maintainability should not come into play, because it's done for production only and is easily automated.

Network latency can't improve much over time because of physical restrictions, whereas bandwidths will. In 10 years' time, it might be better to serve an entire website including images in one single file, than to force several requests.

felgall
04-03-2012, 08:04 PM
I specified the assumptions on the network connection I used to calculate those values, and obviously you'll get different values with different assumptions. I think you don't actually understand how to calculate total download time, though, since you're only talking about your bandwidth and not about network latency, which, as I have pointed out several times now, is becoming the most important factor in page load times. That's the whole reason we're talking about reducing the number of HTTP-requests by combining Javascript files.

I was only calculating the actual minimum time required to download the 200k file on a connection 5 times the speed of the one you assumed and got a much higher figure just for that than you did for your entire calculation. Add in the latency to the figure I had and your figures would be too small by a factor of 10 or more. Perhaps you were assuming the connection speed was in bytes rather than bits.

venegal
04-03-2012, 08:19 PM
Oh, I see. Yes, I did write 1MB/s, and not the equivalent Mb/s speed, so the calculations would be easier to follow.

felgall
04-03-2012, 08:21 PM
Just have a look at your browser's network tab, will you? All current major browsers except Opera download several Javascript files simultaneously, regardless of any defer or async attributes.

Okay I have checked out the network tab in several different browsers.

Opera can download 16 files from one site simultaneously (unless I change that value to something bigger).

Chrome appears to be sharing settings with IE and IE doesn't identify the number of connections it allows (at least not anywhere I can find)

Firefox also has no information on the number of connections allowed on the network tab.

Safari doesn't even appear to have a network tab.

Regardless of whether I can find that information though or not those limits have always applied to all file types except JavaScript since downloading scripts in parallel can easily break their functionality if one depends on the other.


I have also done a search of the internet and have not been able to locate any page that indicates that recent browsers have been modified to break web pages that rely on scripts downloading sequentially by downloading them in parallel.

A simple example would clearly demonstrate how simultaneous downloading would break scripts. You just need two script calls - one to load jQuery and the second with a script that uses it. Assuming the computer doesn't already have a cached copy of jQuery that file would take far longer to download than the other JavaScript file and so the script that intends to use jQuery would download and attempt to run long before jQuery itself has finished downloading.


If one or more modern browsers now do allow scripts to download in parallel can you please provide a link to a web page that explains the change.

blaze4218
04-03-2012, 08:44 PM
http://developer.yahoo.com/performance/rules.html

The problem caused by scripts is that they block parallel downloads. The HTTP/1.1 specification suggests that browsers download no more than two components in parallel per hostname. If you serve your images from multiple hostnames, you can get more than two downloads to occur in parallel. While a script is downloading, however, the browser won't start any other downloads, even on different hostnames. I don't know how old or accurate this information is. But it was the original reason I first migrated my scripts out of my head...

venegal
04-03-2012, 09:11 PM
Okay I have checked out the network tab in several different browsers.


Sorry, I should have clarified (or maybe I did somewhere? This thread is getting long!): I don't mean the network tab in the browser preferences but in the browser's built-in development tools (or Firebug). There you can see for yourself for each page you're visiting how all the files are being loaded. This will look something like the two graphics here http://www.artzstudio.com/2008/07/beating-blocking-javascript-asynchronous-js/, with modern browsers looking more like the second one.



Regardless of whether I can find that information though or not those limits have always applied to all file types except JavaScript since downloading scripts in parallel can easily break their functionality if one depends on the other.


Parallel downloading would break dependencies if the scripts were executed as soon as they are loaded, but that's not the case — just because scripts are downloaded simultaneously doesn't mean modern browsers aren't smart enough to still execute them in order. Page rendering will be blocked, though.


If one or more modern browsers now do allow scripts to download in parallel can you please provide a link to a web page that explains the change.

I don't have any good links at hand — I'm solely relying on what the browsers' network tools are telling me here. If they are lying to me, then I'm wrong, but I don't have a reason to believe that. Since that change isn't breaking anything (apart, maybe, from optimizations implemented against some non-standardized behaviour) or adding any cool new functionality, it might not have been worth communicating it clearly.

venegal
04-03-2012, 09:25 PM
http://developer.yahoo.com/performance/rules.html
I don't know how old or accurate this information is. But it was the original reason I first migrated my scripts out of my head...

The Wayback Machine tells me it's from 2007, and it's a pity there isn't some sort of vendor-controlled best practices living standard. Scripts out of the head still seems feasible for rendering blocking reasons, but there's sadly no easy way of knowing whether (or when) future browser implementations will nullify those efforts by some other sort of trickery.

felgall
04-03-2012, 10:15 PM
[QUOTE=venegal;1211889I'm solely relying on what the browsers' network tools are telling me here. [/QUOTE]

Okay, I found the network tools you are referring to and ran tests in Opera, Google Chrome and Internet Explorer.

From the results shown there you are right - the browsers now don't insist on single threading JavaScript and can download them in parallel. Your specifying Opera as an exception was wrong because it behaved the same as the others.

So that makes my argument for splitting your JavaScript into several files even stronger since you don't even need to add the script tags from JavaScript in order to do parallel downloads. You can achieve it just by specifying several script tags one after the other.

The results on that network tab clearly showed six scripts downloading in parallel taking scarcely longer than just one of those scripts by itself would have taken - and that is taking everything into account since what shows on that tab is the actual live demo that someone asked for earlier in the thread.

This change to the way that browsers download JavaScript makes it even easier to speed up the downloading of JavaScript by splitting it into several separate files.

phat
08-06-2012, 01:54 AM
I don't think anyone here is mocking another's lack of language at all, but one gets quickly tired of a lack of consideration for the viewers having to wade through punctuation salad when we should all be taking pains to be as painstaking as we can.

Minisuit
08-09-2012, 01:24 PM
Yes ! We Can write the all the java script Code in the Single external file and call that file at the top of each file where the concern javascript is needed.

calling the javascript with the absolute path. if the file is in another location and if the javascript file is in the same folder then call it with the file name.

Best Regards,
Navin Patel



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum