Tag Archives: Javascript

Announcing Bootstrap – a simple JS library for loading scripts

I ran into a problem, more than once. The problem was, I needed to use a JavaScript library on only a few pages in a site. It didn’t make any sense to load the library on pages where it wasn’t being used, it just added to the page load time. So I had two options:

  1. Make sure that I only included the library on the pages that needed it. – This wouldn’t work very well because my users could create new pages based on my template. Some would need the library and some would not.
  2. Dynamically inject the script into the DOM only when I needed it from my JavaScript

Script tag injection is nothing new, it’s been around for a long time. Neither are dynamic script loaders. YUI has had one for years, renamed to “get” in YUI3, that I’ve used quite a few times. LabJS and Require.JS are both full featured, well supported script loaders and work great in a wider variety of use cases. NBL was recently updated.

So why did I bother making this one?

Well, it’s really not that hard to do for one thing. I love making micro-libraries like this. It has no external dependencies and the list of possible features I’d like to add is very short.

What I really wanted to do was be able to modify and existing script to dynamically load a script it was dependent on. I could see doing this in several different pages, so I put it in a library.

bootstrap("myLibrary.js", "ScriptTagId");

//or

$b("myLibrary.js","ScriptTagId");

The road map looks a little bit like this.

  • Add a “script loaded” event or , more likely, allow a callback to be passed in and executed once the script has loaded.
  • Add the ability to dynamically load CSS files
  • make the “script tag id” parameter an optional parameter and auto-generate an ID if none is provided
  • Make a cool icon for the project

So, to summarize, this library is really simple. The code is easy to understand right now. I believe is releasing early and releasing often. I didn’t want the lack of features to stop me from releasing. 😉

The code is licensed under the Apache 2.0 license.

Bootstrap on Bitbucket.org

How simple could it be? Lemme post the source code for you.

/**
Copyright 2010 Scott Koon

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
**/

var bootstrap = (function() {
        var bootstrap = function(scriptSrc, id) {
            var scriptTag = document.createElement("script");
            scriptTag.setAttribute("type", "text/javascript");
            scriptTag.setAttribute("charset", "utf-8");
            scriptTag.setAttribute("src", scriptSrc);
            scriptTag.setAttribute("id", id);
            var head = document.getElementsByTagName("head").item(0).appendChild(scriptTag);

        };
        return (window.bootstrap = window.$b = bootstrap);
    }());

A third option for using jQuery templates

Dave Ward has a great post about defining jQuery templates. There’s a third method that he doesn’t mention in his post. The “embedd-and-grab/clone” method. I’ve used this method before for simple element cloning of templates.

<div id="templates">
    <div id="hello">
        <p>Hello, ${name}.</p>
    </div>
</div>

We can create a div, or really any element you want, to hold our templates. What does this gain us? Well if we are using a design tool, we can see what the template will look like before we have to render it. That may make it easier for a designer on your project. We don’t have to make an AJAX call out to retrieve the external template, although Dave talks about how this really isn’t an issue if you have caching set up correctly on your server. And frankly, for the amount of bytes that are in a typical template I can’t imagine any successful AJAX request taking very long.

To use them, you simply grab the templates div and detach it from the DOM. If you assign the detached elements to a var, you can just use jQuery selectors to find the one you want to use. Because, remember most of the jQuery methods return the jQuery object itself.

var templates = ​$("#templates")​​​​​​​​​.detach();
$.tmpl(templates.find("#hello").text(), person);​​​

Why do you want to use the detach method rather than the remove method? The detach method removes the elements from the DOM but keeps any jQuery data associated with them intact. Meaning you can use the $.data() method to add data to your templates and access the data before you compile your templates.
Dave Ward points out that I need to use “tempates.find()” rather than the default selector method on the jQuery object. Noted and updated

Getting started with node.js on Windows

The title is somewhat misleading. As of right now, node.js doesn’t run on Windows. You have to run it on some kind of *nix/BSD based system. But there is a somewhat low footprint way to run it and play around with it on your Windows box.

Step 1 – Download and install VirtualBox orVMWare Player. I chose VirtualBox. It’s free, and supports 64-bit guests.

Step 2 – Download The Turnkey Linux core appliance and unzip it somewhere. This handy little virtual machine is based on Ubuntu and give you a basic command line environment with networking.

Step 3 – Import the Turnkey core appliance into VirtualBox.

turnkey_step_1

turnkey_step_2

Choose the .ovf file in the Turnkey directory you unzipped earlier.

turnkey_step_4

Click next and review the settings, making any changes as you see fit. The defaults should work fine. Then click import.

turnkey_step_3

Once Virtualbox finishes importing the virtual machine, you can start it up.

Assuming your network is configured correctly, the virtual machine will grab an IP from your DHCP server and be ready to go.

turnkey_startup

Step 4 – At this point you can either SSH into the virtual machine or you can connect using the web shell at the address indicated in the startup screen. Initially you can connect using as the root account with no password. You are almost ready to start installing node.js. First type “apt-get update” at the command line to make sure you have all the latest package information.

Step 5 – Install the developer tools you need to get and build node.js. Node.js isn’t packaged as a binary, you have to build it from source. Luckily it includes it’s dependencies and is pretty easy to build. But first we need to get a compiler. Type “apt-get install build-essential” and hit return. A lot of text will fly past, if it asks you if you want to go ahead press “y”.

Step 6 – Install Git. Now you’ve got a compiler installed, we have to install git so we can fetch node.js from the repository. At the command prompt type “apt-get install git”. Once that is complete, type “apt-get install git-core”.

Step 7 – Clone the node.js Git repository. If you want to put node.js is a specific directory, go ahead and make it then “cd” into the new directory. At the command prompt, type “git clone git://github.com/joyent/node.git“.

Step 8 – configure the source for building. type “cd node” and change into the node directory that Git created. Type “./configure”. You may see a few “fail” messages. Don’t worry about them.

Step 9 – Build node.js. Type” “make” at the command prompt. Get a sandwich or a nice cool drink. It doesn’t take very long, but it’s not very exciting unless the Matrix screensaver is your favorite screen saver.

Step 10 – Install node.js and start build applications. Type “make install” once the build is complete. Once that is complete,you can type “node” at the command prompt and you should see the standard help information fly by.

Building a node module or application is beyond the scope of this short tutorial. I suggest reading up at the Node.js site.

Review of “Building iPhone Apps with HTML, CSS, and JavaScript”

This is a great overview of how to style your web site for the iPhone. It provides a basic introduction to HTML and CSS and covers some of the iPhone webkit specific CSS classes and meta tags. There is a brief introduction to the jQuery Touch JavaScript framework. The book also covers using the PhoneGap framework for writing native iPhone applications using HTML, CSS, and JavaScript.

Some of the highlights of this book include a helpful Pro/Con list at the beginning to help you decide if learning Objective-C and using CocoaTouch to write an iPhone app is what you want to do. It would have been nice to also cover, or mention, the Appcellerator mobile framework to build native iPhone applications. There are two great chapters that cover using client side storage in your applications and also techniques for making sure your applications work when the phone is offline.

If you are somewhat familiar with HTML, JavaScript, and CSS and want to write a web based iPhone application I would highly recommend this book.

Goals for 2010

So I’ve been mulling around what I want to do, at least in terms of my development skills and community type stuff, in 2010 (The year we make contact). I figure if I blog them up here, I can refer back to them and check on my progress at the end of the year.

  1. Help out with the MVC Turbine docs
  2. Finish my Ringbinder project and release it
  3. Write a simple little app for use at home in either Clojure or Smalltalk
  4. Continue to learn Python
  5. Write a small app that runs on the Google App Engine
  6. Write a blog post, either here or on my work blog, at least once a week
  7. Redesign this blog
  8. Work on and launch the coderdads.info site I’ve had in mind for a while

I’m sure I’ll come up with more as the year progresses and I, hopefully, finish up these tasks.

A new JavaScript CDN from Microsoft

Microsoft announced a new Content Delivery Network for their ASP.NET AJAX JavaScript libraries and jQuery. This means that instead of hosting those libraries on your server, you can just link to the versions on Microsofts server. I made a simple page that takes a querystring parameter (q=) and uses the ASP.NET AJAX dynamic templates to bind search results from a call to the Bing API.

The money lines in the source are the following:


<script type="text/javascript"
src="http://ajax.microsoft.com/ajax/beta/0909/MicrosoftAjax.debug.js"></script>

<script type="text/javascript"
src="http://ajax.microsoft.com/ajax/beta/0909/MicrosoftAjaxTemplates.js"></script>

These two lines tell the browser to load the MS AJAX scripts from the CDN. There are some security concerns around the fact that the files are served from the microsoft.com domain. Both Google and Yahoo serve there files from a separate, non-cookied domain (googleapis.com and yahooapis.com respectively). Hopefully, these fears will be unfounded.

On a side note, it is surprisingly easy to use the Bing API if you are familiar with script tag injection. The easiest way is to put an empty script tag in your page.

<script id="jsonResults" type="text/javascript"></script> 

And then just create your Bing URL and set the script elements src attribute to the URL you created.

			function MakeSearchRequest(searchPhrase)
			{
				var req = "http://api.bing.net/json.aspx?"
	            + "AppId=" + YOUR API KEY GOES HERE
	            + "&Query=" + searchPhrase
	            + "&Sources=Web"
	            + "&JsonType=callback"
	            + "&JsonCallback=BuildResults";
				
				$get("jsonResults").src = req;
			};