Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Page 1 of 8 123 ... LastLast
Results 1 to 15 of 106
  1. #1
    Regular Coder
    Join Date
    Oct 2010
    Posts
    157
    Thanks
    2
    Thanked 1 Time in 1 Post

    How to combine Javscripts into one JS

    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-
    Code:
    <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-
    Code:
    &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-
    Code:
    <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

  • #2
    Regular Coder
    Join Date
    Apr 2005
    Location
    Texas
    Posts
    448
    Thanks
    24
    Thanked 63 Times in 63 Posts
    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/closur.../api-tutorial3
    Allwisend bin ich nicht, doch viel ist mir bewursst
    -Goethe

  • #3
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,079
    Thanks
    203
    Thanked 2,542 Times in 2,520 Posts
    Is there in fact any practical advantage in combining multiple scripts into one external file? Run faster - a few milliseconds perhaps.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #4
    Regular Coder
    Join Date
    Oct 2010
    Posts
    157
    Thanks
    2
    Thanked 1 Time in 1 Post
    Quote Originally Posted by blaze4218 View Post
    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/closur.../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?

  • #5
    Regular Coder
    Join Date
    Oct 2010
    Posts
    157
    Thanks
    2
    Thanked 1 Time in 1 Post
    Quote Originally Posted by Philip M View Post
    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.

  • #6
    Regular Coder
    Join Date
    Apr 2005
    Location
    Texas
    Posts
    448
    Thanks
    24
    Thanked 63 Times in 63 Posts
    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.
    Allwisend bin ich nicht, doch viel ist mir bewursst
    -Goethe

  • #7
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,079
    Thanks
    203
    Thanked 2,542 Times in 2,520 Posts
    Quote Originally Posted by blaze4218 View Post
    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.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #8
    Regular Coder
    Join Date
    Apr 2005
    Location
    Texas
    Posts
    448
    Thanks
    24
    Thanked 63 Times in 63 Posts
    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...
    Allwisend bin ich nicht, doch viel ist mir bewursst
    -Goethe

  • #9
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,642
    Thanks
    0
    Thanked 649 Times in 639 Posts
    Quote Originally Posted by blaze4218 View Post
    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.
    Last edited by felgall; 03-27-2012 at 09:31 PM.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #10
    Regular Coder Lerura's Avatar
    Join Date
    Aug 2005
    Location
    Denmark
    Posts
    946
    Thanks
    0
    Thanked 129 Times in 128 Posts
    Quote Originally Posted by cryoffalcon View Post
    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:
    Code:
    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.

  • #11
    Regular Coder
    Join Date
    Apr 2005
    Location
    Texas
    Posts
    448
    Thanks
    24
    Thanked 63 Times in 63 Posts
    Quote Originally Posted by felgall View Post
    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
    Quote Originally Posted by blaze4218 View Post
    It's up to you to decide what is best for your needs
    Quote Originally Posted by lerura View Post
    Do your own evaluations on what is best, instead of just listening to recommendation.
    Allwisend bin ich nicht, doch viel ist mir bewursst
    -Goethe

  • Users who have thanked blaze4218 for this post:

    Philip M (03-28-2012)

  • #12
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,642
    Thanks
    0
    Thanked 649 Times in 639 Posts
    Quote Originally Posted by blaze4218 View Post
    '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.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #13
    Regular Coder
    Join Date
    Oct 2010
    Posts
    157
    Thanks
    2
    Thanked 1 Time in 1 Post
    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.

  • #14
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,079
    Thanks
    203
    Thanked 2,542 Times in 2,520 Posts
    Quote Originally Posted by cryoffalcon View Post
    i am an accountant
    Really? Most accountants are literate and know that the personal pronoun I is a capital letter.

    Quote Originally Posted by felgall View Post
    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

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • Users who have thanked Philip M for this post:

    blaze4218 (03-28-2012)

  • #15
    Regular Coder tpeck's Avatar
    Join Date
    Oct 2002
    Location
    Sydney, Australia
    Posts
    877
    Thanks
    53
    Thanked 6 Times in 5 Posts
    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.
    The difference between genius and stupidity is that genius has its limits. (Albert Einstein)


  •  
    Page 1 of 8 123 ... LastLast

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •