# Using graphics and scripting effectively

If an application uses a lot of resources, keep the graphics as light as possible and maintain a balance between good graphics and resource consumption. You can replace some graphical special effects with code to ensure better performance. For example, you can write code instead of inserting graphics or animation to create highlighted menu options or sparkling stars. You can use JavaScript optimization techniques that improve the user experience of Web applications on mobile devices. Generally, these are the same techniques that are used on desktop browsers.

### Optimizing image size

Smaller images in terms of both pixel size and color depth conserve memory and load faster. A color depth of 16 bits is a good compromise between looks and size. The screen resolution defines the actual size of graphics on the display. For example, a graphic that looks very small on a large display may become too small on a device with the same number of pixels but a smaller display.

When possible, create images in the intended maximum size, because their quality degrades when you scale them up. Also, high-contrast edges in a image might result in poor quality when scaling down.

You can allow the Web Runtime (WRT) rendering engine to automatically scale images to fit different screen sizes, based on the `HTLM IMG` tag width and height parameters. However, this can result in poor image quality. For better quality, use a desktop imaging tool to scale images. First convert the image to 24-bit color mode, for example to PNG-24. The increased color depth allows a good scaling tool to add color gradations to perform anti-aliasing on the final image.

### Optimizing JavaScript

You can optimize JavaScript in the following ways:

- Use external and not internal JavaScript.

      <script src="url_to_js" type="text/javascript"/>

  External JavaScript files can be cached independently of HTML files, which is good because JavaScript is usually more static than HTML. External JavaScript can be shared between pages. Remember to set the `Expires` header.

- Minimize the size of the final output JavaScript code, for example with automation tools. Strip comments from your code. Strip excess white space. Minimize and pack the code, using GZIP compression. Remember to consider the good balance of the XHTML structure and unobtrusive JavaScript.

- Do not run long-running JavaScript functions on page load. Web applications do not multi-task and the browser is thus blocked from the user input for the duration. If you have a long running script, try to speed it up, for example by profiling the functions and improving the XHTML structure.

- Do not use JavaScript where CSS can be used instead. For example, implement menus and rollover images with CSS instead of JavaScript.