Actually, there is a way to do that. Working on our own Client SDK we’ve come up with a good (we hope it’s good) solution how to arrange great amount of JS files in some structural way. We also wanted to minimize pages’ weight by including JS code that matters for the current page to avoid the need to include your X hundred Kb .js file for just a couple of functions in it.
There are some rules you have to follow to get your JS fitting into packages:
- Package structure has to reflect to file system folder structure. net.codemate.sdk.core.base package reflects to net/codemate/sdk/core/base folder structure under package root (see below).
- Each JS file should contain only one interface or class and that file should be named as a class name (the same as in Java).
- Naming conventions for methods, classes and packages are the same as for core Java.
Packaging system loads required JS files using AJAX technology and evaluates their content to make definitions of the files available for using.
First of all you need to include core js file to get packages working on your page:
This makes available following methods and objects:
- packageManager – core object which handles the package structure.
- __package_root(url) – defines root of the package. Few roots can be defined. url – standard URL (e.g. http://codemate.net/sdk/src/js)
- __package(path) – package declaration. Similar to package definition in Java. path – Defines packaging tree (e.g. net.codemate.sdk.demo.Foo)
- __import(path) – loads script relatively to one of the defined roots. path – defines route from root to the script. (e.g. net.codemate.sdk.core.base.Class)
Let’s take a look at example.
Now step by step
__import('net.codemate.sdk.demo.*'); does actual import of necessary files. You can use “*” or a particular class you want to import e.g.
That’s actually it. This is how we use packages in our project. Actually, we use more than just packages, we use object-oriented paradigm, we use JsUnit and a lot more custom developed things.
I can’t provide lots of implementation details due to our customer’s contract restrictions. But we’re ready to answer questions and shed some light in comments.