Question

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();
}
Was it helpful?

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).

OTHER TIPS

I believe you are mixing two concepts in the code you're wrtiting. Service Locator do not handle service instatiation. It allows to keep a record of services available to the system.

In that sense, the service locator should be something like

var ServiceLocator = new function () {
    var self = this;
    var services = {};

    self.register = function (key, service) {
        services[key] = service;
    };

    self.resolve = function (key) {
        return services[key];
    };
};

Then, services need to be created and registered, but as you need different services per page, a factory that pre-builds them all won't work. You could make a service register itself like

var RetailService = function () {
    // service definition        
};
ServiceLocator.register('retailService', new RetailService());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top