Optimer, komprimer og finjuster ... /Sik Optimize, tweak, and tune ... /Sik
This article shows you how to make your OpenLayers map applications more efficient by drastically reducing the size of this script file.
In the two years since I started to use OpenLayers, it has doubled in size to 711K (version 2.8). This growth has been due to the addition of a growing number of data sources, layer types, standard controls, and languages. These are all useful things which increase the utility of OpenLayers, but they also result in code bloat. Few if any applications use more than a small number of the available features. Of course each application uses a different subset of features! Would it not be great if we could cut OpenLayers.js down to just include the features that we require? We can, by using the build scripts which are provided with OpenLayers.
The standard OpenLayers package can be downloaded from the main OpenLayers website. In addition to the main OpenLayers.js script, this package includes a complete set of component scripts and a build environment. We shall use the scripts in this build environment to create a custom OpenLayers.js with just the support that we require. The following examples assume you are working with OpenLayers v2.8. You may need to change the exact directory names to match the version you are using.
Make sure you also have Python installed because this is used by the main build script. You will also need to use a command line environment. The Windows command prompt should be usable, but I used FreeBSD (as used by my web host).
Download and uncompress the latest version of OpenLayers. Navigate to the OpenLayers root directory (~/OpenLayers-2.8 in this example). Note that this directory holds the standard build of OpenLayers.js along with auxiliary files (eg. the standard theme). It also holds other directories that you might find useful, such as the documentation and source components. We are interested in thebuild sub-directory. Navigate to this. You will see a number of explanatory text file notes, three cfg configuration files, and two Python scripts called build.py and buildUncompressed.py. These simply build a new OpenLayers.js using a particular configuration file. Normally, you will use build.py which compresses the final output, but buildUncompressed.py might be useful if you wish to edit or otherwise amend the resulting script.
Running the script is very simple. In a Unix-like shell, simply run "./build.py yourconfig.cfg" where yourconfig.cfg is the name of the configuration file to use. The script takes a few seconds to run, and provides a list of the included components, and further components that are required by these. The resulting OpenLayers.js is written to the build directory. [...]