简体   繁体   中英

How do I include external javascript files in bookmarklets?

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?

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());
})();

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