Amit
Amit

Reputation: 3990

Adding jQuery to a 3rd party page fails

I am trying out a few things, and among those I tried to insert jquery on a site, namely, http://www.tesco.com/wine.

For some reason, I was not able to able access jQuery even though I was able to successfully append a new script tag to the body element. Also, the page seems to have a window.$ function that I tried to delete with delete window.$. This, seems to return false for me. How do you make something undeleteable?

Here is the code I used to append the jQuery script to the document:

var s = document.createElement('script');
s.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js";
document.body.appendChild(s)

It is working on other pages.

Upvotes: 1

Views: 90

Answers (2)

Andy E
Andy E

Reputation: 344575

After discussing this in JavaScript chat, Tim Stone discovered that the JS on the page adds its own implementation of Object.prototype.extend - which breaks the jQuery script. To fix it (but potentially break another script on the page), you can delete that before adding jQuery:

delete Object.prototype.extend;
var s = document.createElement('script');
s.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js";
document.body.appendChild(s)

$ is already defined on that page with the following function declaration:

function $(A){return document.getElementById(A)}

It is not uncommon to alias document.getElementById() with $() — in fact, Firebug and WebKit's developer tools do this in their console.

It is not deletable, because it is declared as a function statement and not an object property. While delete may work in some browsers, it shouldn't and won't in others. That being said, I was able to override the function with a simple assignment:

$ = function () {}

When jQuery loads, it creates the jQuery namespace and aliases this namespace with $. Therefore, if something else on the page is overriding $, you can still use jQuery().

Upvotes: 4

Jonas Høgh
Jonas Høgh

Reputation: 10874

If $ is already defined, you can always use jQuery instead.

Upvotes: 1

Related Questions