简体   繁体   中英

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.

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() .

如果已经定义了$则可以始终使用jQuery

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM