Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Cross Browser Issues
Expertise: Beginner
Oct 18, 1999



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Optimize Pages Containing Numerous JavaScript Functions

I have produced a bunch of DHTML library functions that work in a cross-platform environment, down to the point of redefining the layer object in Netscape and writing customized event handlers. Now that I can do virtually anything I want with layers, the sheer amount of code this requires is making my pages amazingly heavy (for example, something that should be about 30 KB has now blown up to about 80 KB). How can I optimize my code so that I can get my page sizes down to a reasonable amount?


It sounds as if you have a large number of JavaScript functions, and unfortunately, this will continue to add to the size of the page if you embed the JS in every HTML page. One thing you can do is break your JavaScript down into manageable and discrete groupings of functionality, place these groups in separate JavaScript files (files with .js extension), and only include the functionality you need in each page.

For instance, I have a JavaScript source code file that contains a set of cross-browser objects that perform basic DHTML movements, such as hiding or showing an element, or placing an element in a specific position. I have another JavaScript source code file that contains another set of objects that perform complex animations. This second set of objects uses the objects defined in the first file to perform each cross-browser DHTML action. However, this second file also includes the timing and sequence management to control the entire animation.

Unless I need animation, I don't include the animation JS file in a Web page. I can use the single-action objects for any DHTML I need, and the page doesn't have the extra download size of including both groups of functions:

However, when I do need the animation, I include both JS files within the Web page:

JavaScript files become part of the Web page so you don't have to code all functionality in one single large block of text. In addition, with some browsers, JavaScript source code files can be cached. Try breaking your code into reusable components that you can include as needed into a page.

DevX Pro
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date