现在的位置: 首页 > 综合 > 正文

Using Prototype to Load Javascript Files

2012年10月24日 ⁄ 综合 ⁄ 共 2356字 ⁄ 字号 评论关闭

The calendar on this site only appears on pages that show blog-related information. That calendar is enhanced with Javascript allowing you to change the month displayed by the calendar without reloading the rest of the page. So, in order to ensure that these enhancements would be available everywhere the calendar is, I figured I had two options:

  1. Code the inclusion of the Javascript file into every page which requires it. While a good solution, and one that has worked well in the past, sometimes it can be difficult to remember or realize that you've forgotten to include the file when you add new pages that require it.
  2. Find a way to automatically include the file when it's needed. This would avoid the need to remember the need to include it when adding new pages that require it, but would result in a little more Javascript going on when the page loads.

This past weekend, with a little help from the Prototype Framework, I found a solution for #2 above which I am, for the moment, quite pleased with. The following snippet assumes the most recent version of Prototype as of this writing (1.6.0.2):

document.observe("dom:loaded"function() {    var calendar = $("calendar");    if(calendar) {        var script = new Element("script", { type: "text/javascript", src: "/path/to/calendar.js" });        document.observe("calendar:loaded"function() { new Calendar(calendar); });        $$("head")[0].insert(script);    }});

Here's, essentially, what it does:

  1. Uses the custom dom:loaded event which, since Prototype 1.6.0, determines when the DOM is ready for manipulation to call the anonymous function defined in the snippet.
  2. That function attempts to get a reference to the calendar. If it can't, then nothing else happens. This makes sure that we don't include the calendar Javascript unless we need to.
  3. Once we've found a calendar:
    1. Create a new
    2. Tell the document to observe the calendar:loaded event, which is fired from the bottom of teh calendar's javascript.
    3. Insert the javascript file into the head of the document.

It's #3.2 that is the most important step. The calendar.js file makes sure to use the Prototype fire() method to create the custom calendar:loaded event. Thus, when the browser is done performing the necessary work required to insert the calendar.js file, it'll fire the custom event, which will be caught by the document object to instantiate the newly inserted Calendar.

In other words, with a creative use of Prototype's Event.observe() and Element.fire() methods, we not only include Javascript files only when they're needed, but also ensure that we don't attempt to use the code within those files until the browser is ready for it to be used.

抱歉!评论已关闭.