devxlogo

Optimize Pages Containing Numerous JavaScript Functions

Optimize Pages Containing Numerous JavaScript Functions

Question:
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?

Answer:

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.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist