Text

Javascript invisible character hack

I got an idea for a bit of a hack that I though would be cool, using invisible ascii codes to segment html.

For example:

 test 1


function (som) {
    something();
}


With the javascript:

jQuery(function () {
    var c = $('#subject').html();
    c = c.replace(new RegExp(String.fromCharCode(1)+'(.*)'), "<strong>$1</strong>");
c = c.replace(new RegExp(String.fromCharCode(2)+'([\\s\\S]*?)'+String.fromCharCode(3)), '<pre>$1</pre>');
});

I’m not really sure how this is useful but I tested it in Chrome, Safari, Firefox and Opera.

Image
Screenshot of part 6 of my series Node.js + HTML5 + Socket.io = Game. Code is available  on github. Tutorial coming soon.



ok

Screenshot of part 6 of my series Node.js + HTML5 + Socket.io = Game. Code is available on github. Tutorial coming soon.

ok

Text

Javascript Image Preloader

Browsers offer the ability to provide a callback for when a given image has loaded, but what if you want to run a single callback after multiple images have loaded? The following code does exactly that.

Usage


var loader = new Loader();
var image1 = loader.add('img1.jpg');
var image2 = loader.add('img2.jpg');
loader.onComplete(function () {
    // What to do on complete
});
loader.start();

The class


function Loader() {

	this.images = new Array();
	this.onCompleteCallback = function () { };	
	this.numLoaded = 0;

	this.add = function (path) {
		var loader = this;
		var img = new Image();

		img.onload = function () {
			loader.loaded();
		}

		this.images.push({img: img, path: path});

		return img;
	}

	this.onComplete = function (callback) {
		this.onCompleteCallback = callback;
	}

	this.loaded = function () {
		this.numLoaded++;

		if (this.images.length == this.numLoaded) {
			this.onCompleteCallback();
		}
	}

	this.start = function () {
	    for (var i=0; i<this.images.length; i++)
	        this.images[i].img.src = this.images[i].path;
	}

        return this;
}