Window.attachEvent() (Method)

A means of attaching events to windows and documents.

Availability:

JScript - 5.0
Internet Explorer - 5.0
Property/method value type:Boolean primitive
JavaScript syntax:IEattachEvent(anEventName, anEventHandler)
IEmyWindow.attachEvent(anEventName, anEventHandler)
Argument list:anEventHandlerA reference to an event handler function
anEventNameThe name of an event to be handled

This is part of the behavior handling in MSIE which involves the use of style sheets and .htc files. It is a way of binding a function to an event so that when the event fires, the function is called. It can be applied in a more general way than just with behaviors.

The mechanism is quite straightforward to apply. First, create a style that can be used to attach the script to an HTML element. In that style, refer to a fragment of JavaScript contained in an external file. That external file is called an HTML Component or HTC. It is stored in an .htc file. The .htc file is invoked in a similar way to the <SCRIPT SRC="..."> mechanism.

Then, in that .htc file, you create a handler script that attaches itself to whatever event you want the handler to be connected to. This attachEvent() method is what is used to accomplish that.

When the browser loads the page, the .htc file is loaded and installed and the script registers itself with the event trapping mechanisms in the browser. When the event fires, the handler script in the HTML component is executed.

There are many advantages regarding code re-use and efficiency that this technique facilitates. However, the downside is that the HTML components can result in a large number of additional requests for separate items from the web server and this can be detrimental to performance. So detrimental, in fact, that it is possible that the items may not all be loaded by the time the user is ready to interact with the page.

Two events are triggered which can be used to manage this scenario more elegantly. These are the onContentReady and onDocumentReady events. They are sent to the behavior script as a notification so you can take some action internally to prime your handler. These events would typically cause the behavior handler to set flags internally that can be checked when the handler is invoked by the user. Those flags can then lock out any interaction with the page until it is known that the content of the element and the rest of the document have been loaded. At the very least, the handler should wait until the first receipt of an onContentReady event.

Warnings:

See also:<STYLE>, Document.attachEvent(), Document.detachEvent(), Window.detachEvent()