Reputation: 3046
I'm making a cdn for a bunch of scripts I've written for work. I used to have to distribute them and each person get the file and install it on their computer, but I'm moving them to an amazon cloudfront/s3 instance.
I'll be using this to inject the bookmarklet: http://allben.net/post/2010/01/30/CSS-JavaScript-Injection-Bookmarklets
However, the old way I was doing this I used the jquery bookmarklet generator. This is different than that and I am unaware how to include jquery should I want to use it.
Here is an example script:
javascript:(function(){var%20s=document.createElement('script');s.setAttribute('src','cdn.domain.com/scripts/somescript.js');document.getElementsByTagName('body')[0].appendChild(s);})();
That goes in a bookmark.
The script:
alert($(somecontainer).size());
Obviously this doesn't work because the bookmarklet is no longer injecting jquery. So, what is the best way to go about this?
Upvotes: 1
Views: 722
Reputation: 3517
The problem you are facing, I guess, is that the jQuery bookmarklet generator does not make $
available within the page. It keeps the jQuery variable isolated within a function and then removes jQuery entirely from the page after running.
Below is a modified version of code from here: http://benalman.com/projects/run-jquery-code-bookmarklet/ which should work.
function (e, a, g, h, f, c, b, d) {
if (!(f = e.jQuery) || g > f.fn.jquery || h(f)) {
c = a.createElement("script");
c.type = "text/javascript";
c.src = "http://ajax.googleapis.com/ajax/libs/jquery/" + g + "/jquery.min.js";
c.onload = c.onreadystatechange = function () {
if (!b && (!(d = this.readyState) || d == "loaded" || d == "complete")) {
var s = document.createElement('script');
s.setAttribute('src', 'cdn.domain.com/scripts/somescript.js');
document.getElementsByTagName('body')[0].appendChild(s)
}
};
a.documentElement.childNodes[0].appendChild(c)
}
})(window, document, "1.3.2")
Keep in mind that this will replace any jQuery
and $
variable on the page. If you need to run the bookmarklet on pages that use those variables already, use jQuery.noConflict(1)
. For example _jq = e.jQuery.noConflict(1)
will let you use _jq
instead of $
and will return the original $
and jQuery
to their original values. Example:
alert(_jq(somecontainer).size());
If you want to use noConflict but also use $ in your .js code, wrap your code in a function and create a locally scoped $
. Example:
(function(){
var $ = _jq; // this $ will not affect any $ that exists outside this function.
alert($(somecontainer).size());
})();
Upvotes: 1