Screencasts

Creating a Bookmarklet with Remote JavaScript Code

Show Notes

In our previous video in the bookmarklet series we showed you how to create a simple bookmarklet where all the code was contained wholly within the bookmarklet itself.

In this follow-up screencast we’re going to show you how to include source code from a JavaScript file stored on a remote server.

What you'll Learn

  1. How to create a Bookmarklet with code stored in an external JavaScript file

Script

In our previous screencast in the bookmarklet series we showed you how to create a simple bookmarklet where all the code was contained wholly within the bookmarklet. In this screencast we’re going to show you how to include source code from a JavaScript file stored on a remote server.

The main reason you’d want to do this is so that you can update the bookmarklet without telling your users to manually update the bookmarklet themselves.

We’re going to create a bookmarklet that performs the same browser resizing as in the previous screencast, but this time instead of it being included in the bookmarklet itself, we’re including it from a remote source so that we can transparently update it to fix any bugs or include support for new browsers.

First off we need to create our anonymous function where we’ll put the code to remotely load our JavaScript. We’re using a javascript file for now, but we’ll remove any returns and indentation before embedding it in to the link.

(function(){
    
})();

Then we need to create a script tag where we’ll include the source of our remote JavaScript file.

(function(){
    var s = document.createElement('script');
    s.src = 'http://bookmarklet-720pify.heroku.com/js/720pify.js';
})();

Then we want to append our script tag to the body of the document we’re on when the bookmarklet is pressed.

(function(){
    var s = document.createElement('script');
    s.src = 'http://bookmarklet-720pify.heroku.com/js/720pify.js';
    document.body.appendChild(s);
})();

And that’s it. So let’s remove any indentations and returns and place that in our link.

<a href="javascript:(function(){var s = document.createElement('script');s.src = 'http://bookmarklet-720pify.heroku.com/js/720pify.js';document.body.appendChild(s);})();">720pify</a>

Remember to include the javascript: at the beginning of the link.

It’s also worth mentioning we’re still wrapping our 720p-ifying code in an anonymous function so that all variables within our bookmarklet code are within the scope of our functionality. This is so that it doesn’t interfere with any other JavaScript that might already be loaded in the DOM.

So once we drag the link into our bookmark bar, navigate to another page, and then press it, our bookmarklet works!

Next time we’ll show you how to use jQuery in your bookmarklet, so you can write less and do more!

Thanks for watching.

← Latest Episodes

blog comments powered by Disqus