views:

16

answers:

1

I am using the Prototype javascript framework. I have included it in a javascript code snippet that I allow people to copy and paste onto their websites. There is a possibility that their website already includes Prototype or they wanted to include the snippet multiple times. In both cases, Prototype will be defined twice and, as a result, IE7 will not function. It will say "Object does not support this property or method" on nearly any Prototype library function call. I tried this:

if (typeof(Prototype) === 'undefined') {
   alert('including Prototype');
   // minified Prototype code here
}
alert('running my code');
// all my code here

When I ran this, only "including Prototype" was alerted, but "running my code" never got alerted. Why?

+1  A: 

only "including Prototype" was alerted, but "running my code" never got alerted. Why?

I don't know without seeing the code—do you get anything in the JavaScript error console?—but one possibility is that something in the code relied on being in an unadorned global scope. For example the function statement may not be used inside an if in standard ECMAScript. What actually happens if you try is browser-dependent, but typically it may override a previously-declared version of the function even if the if clause does not evaluate true.

This problem could be solved by putting Prototype in its own <script> block that's inserted into the page via DOM methods or document.write before the main script executes. However:

I have included it in a javascript code snippet that I allow people to copy and paste onto their websites.

Yeah, I really wouldn't do that. Using more than one wide-ranging, intrusive framework like Prototype or jQuery on a single page is a recipe for conflict and potentially hard-to-debug problems. (Same with two copies/versions of the same framework.)

When you are a pastable snippet you are a guest in another webmaster's house need to have as low a footprint as possible. IMO that means you should not use any framework.

bobince