Search code examples
javascriptservice-locator

Javascript and service locator and including js files


I made a service locator class to access different service classes in my javascript application, but i'm not sure how effective a service locator is in javascript, because of the include files i have to include on every page.

For example i have two services in my service locator, but what if i only need to access one of the services on a page, then i still need to include both js files. Is that good javascript design? Two includes properly doesn't effect performance noticebly, but if i expand my service locator with 10 services, then i need to include 12 js files, eventho i might only need to acces one or two on a page. How do i do this the best way in javascript?

Here is my service locator code:

function serviceFactory() {
    this.constructor = function () {
        this.retailService = new retailService();
        this.outlookService = new outlookService();
    }

    this.constructor();
}

Solution

  • There are several solutions that can include your Scripts dynamically when needed.

    1. RequireJS
    2. Head.js
    3. $.getScript()

    But you should note that browsers cache a lot, which means after they downloaded something once they won't do it again for some time (how long exactly depends on browser and webserver configuration).