views:

88

answers:

3

I need some scripts inside an existing site's scripts.js.

This site has been online for ages, and I can not touch the scripts file.

I am including it standardly in another page. There are numerous jQuery calls in the scripts file. The place I include it does not have jQuery.

I want to void all $() type things. I tried this...

$ = function() { };

before I included scripts.js and it didn't seem to work. I am still getting errors like

$(document) is undefined

Is there a way to void all these jQuery calls?

Thanks

+1  A: 

try

window.$ = function(selector, context) {alert('eating the calls to $');}

in your file that you're including before the scripts.js file. This is how it's defined in jquery so should take care of the selector syntax.

You may need to define other overrides to cater for the $.method() type calls tho

lomaxx
Thanks for having a go, but I think I was trying something pretty stupid in the end. +1 for your effort anyway.
alex
Adding "selector" and "context" to the argument list is totally pointless...
J-P
+2  A: 

Even if you do get that working, you'll still have problems because the code was written with the assumption that jQuery was present. Yes, you can avoid $ is null or not defined errors on lines like this:

$('div.foo');

But there's no point in just writing that line: there will always be actions on the returned object:

$('div.foo').html('blah');

After the NOP jQuery function, you'll get a "html" is not a function error, and so on. The only way you could do it would be to fill out a skeleton of every possible jQuery method, making sure each one returns itself when appropriate.

...or just rewrite it properly...

nickf
The more I thought about it, the more I realised it'd be easier to pick out the few functions I need.
alex
+1  A: 

Well, it's no surprise that $(document) is undefined, since you're not returning a value from your placeholder function. Thus, things like $(document).ready(function(){}); will naturally be errors.

Basically, if I understand right, you need $ to be a function that does nothing and returns another object where calling any member function does nothing. Further, calling member functions of $ itself (e.g. $.ajax()) should have the same behavior.

You can do this with __noSuchMethod__, which is unfortunately non-standard:

window.$ = function()
{
    var doNothingObj = new (function() 
    {
        this.__noSuchMethod__ = function() 
        { 
            return doNothingObj; 
        } 
    })();
    return doNothingObj;
};
window.$.__noSuchMethod__ = window.$;

This will allow arbitrary chains:

$(document).ready(function(){});
$("#foo").animate().animate();
$.ajax({ url: "file.html"});

etc.

Of course, a much saner solution is to refactor the code that uses jQuery.

Matthew Flaschen
Thanks, interesting but I did go with the saner solution :) +1
alex