Created
February 17, 2010 06:01
-
-
Save kentbrew/306351 to your computer and use it in GitHub Desktop.
Evolving a JavaScript Widget
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<html> | |
<head> | |
<title>My Javascript Widget</title> | |
</head> | |
<body> | |
<script src="widget.js"></script> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// the evolution of a widget | |
// coded by Kent Brewster | |
// http://kentbrewster.com | |
// bare minimum primordial widget | |
// - find the SCRIPT tag that called you | |
// - create a DIV placeholder | |
// - delete your calling SCRIPT tag | |
(function (d, w) { | |
// localVar $ = window[someRandomThing] = an empty object | |
// there are lots of ways to make random names; this one is simple | |
// and feeds my vanity a bit by using my initials :) | |
var $ = w['kb_' + new Date().getTime()] = {}; | |
// local pointer back to document | |
$.d = d; | |
// our main function | |
$.f = (function () { | |
return { | |
init : function (findMe) { | |
var i, s; | |
// get all the SCRIPT tags on the page | |
s = $.d.getElementsByTagName('SCRIPT'); | |
// start looping through them | |
for (i = 0; i < s.length; i = i + 1) { | |
// found it! | |
if (s[i].src.match(findMe)) { | |
// create a node | |
$.s = $.d.createElement('DIV'); | |
$.s.innerHTML = 'Hello, world!'; | |
// slide it in before the SCRIPT tag | |
s[i].parentNode.insertBefore($.s, s[i]); | |
// remove the SCRIPT tag | |
s[i].parentNode.removeChild(s[i]); | |
// stop immediately, so other instances can fire too | |
break; | |
} | |
} | |
} | |
}; | |
}()); | |
// we need to match as much of the script's name as possible | |
$.f.init(/widget\.js$/); | |
// in production, do something like this: | |
// /^https?:\/\/[^\/]*mydomain.com\/mypath\/myscript.js$/; | |
}(document, window)); | |
// up next: passing configuration variables | |
// http://gist.github.com/313105 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment