0

This is a question looking for an approach / solution in order to solve the following requirement:

  • You have a website running jQuery
  • All jQuery functions on your site can be grouped into two groups: a) Business relevant logic (local functions, like navigation, etc.) and b) functions for fetching less important content (like advertisements), we call a) GROUP L and the other GROUP E (for external).
  • The aim is to make sure that delays in group E do not hinder group L to execute, so group L and E should run in parallel, not impacting each other.

How can this be achieved?

Very simple example:

Local GROUP L :

<script>
  $(document).ready(function() {
    ... local functions, e.g. event listeners for your local navigation ...
  }
</script>

GROUP E: any javascript provided by external parties

<script>
  $(document).ready(function() {
    ... external java script code, e.g. Advertiser JS-snippets ...
  }
</script>
basZero
  • 4,129
  • 9
  • 51
  • 89

2 Answers2

1

You can accomplish this with module patterns:

(function(main, $, undefined){

    GROUP_L = {
        group_l_variable : null,
        group_l_function : function(data){
            //... local functions, e.g. event listeners for your local navigation ...
        },
    }
    GROUP_E = {
        group_e_variable : 'cats',
        group_e_function : function(data){
            //... external java script code, e.g. Advertiser JS-snippets ...
        },
    }

}(window.main = window.main || {}, jQuery));

You can call these anywhere; try it out in your console:

>>GROUP_E.group_e_variable
>>'cats'

>>GROUP_E.group_e_function(my_data)
>> //whatever your function does

Plenty more ways to do this, this particular way happens to be my favorite.

More on module patterns : http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html

Mike Johnson Jr
  • 776
  • 1
  • 13
  • 32
1

Just in case you don't know about it. I personaly recommend you to learn AMD (Asynchronous Module Definition) using RequireJS. You could even load individual pieces of jQuery using AMD. Cheers.

Adi Utama
  • 98
  • 5
  • Thanks for this pointer, sounds very interesting. As you can imagine, the javascript in the above GROUP E is provided by external parties, so I don't have control over them (and they probably use the global variables $, jQuery), so I am actually looking for isolating MY OWN CODE from that external code... – basZero Jan 15 '15 at 09:38
  • what about using window.onload() for activating the code of group E? see [another question here on stackoverflow](http://stackoverflow.com/questions/25877461/load-google-ads-after-entire-page-has-loaded) – basZero Mar 30 '15 at 14:42