Archive for the ‘Web Development’ Category

console.log helper function

Thursday, April 4th, 2013

I have often found it tricky to get a ‘just-right’ console.log wrapper in JavaScript. I would prefer to just type log, but writing a wrapper function is a little trickier than at first glance. A variation of this used to exist in the HTML5 Boilerplate plugin.js but is now missing.

I have two versions – one is bigger, and is intended for an application – it stubs out console methods when they don’t exist, and exposes a log function to the window. The second is portable – it is meant for use inside of plugins.

The neat thing about this technique is that this preserves the original line of code inside of the console.log statement, rather than the line in which the log function is declared.


The code is in a gist, which is also embedded below:

Devtools Colorpicker Palette

Saturday, February 2nd, 2013

I’m still trying to figure out how to get a list of all the colors in use on a page from within devtools, but I’ve been hacking together a little demo with a custom Web Inspector frontend that loads a color palette on the side.

When you click one of the swatches, it sets the current color of the element. The idea is that it would include all the colors in your page, maybe ordered by most used. Possibly could even get more advanced and suggest a set of complementary or analagous colors based on your current selection.

A prototype implementation of a palette using color swatches within devtools

A prototype implementation of a palette using color swatches within devtools

jQuery UI 1.9 Boilerplate

Wednesday, October 17th, 2012

jsbin has made having to remember some of these links less important. However, with jQuery UI 1.9 coming out, there are some CDN links that aren’t working. Here is the updated boilerplate I use to quickly test out a jQuery UI project. If all goes well, you should have a dialog that you can drag around and resize.

<!doctype html>
<html>
<head>
  <title></title>
 
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.9.0/themes/base/jquery-ui.css">
 
  <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
  <script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.0/jquery-ui.js" type="text/javascript"></script>
 
  <style type="text/css">
    #modal {
	 background: orange;
    }
  </style>
 
  <script type='text/javascript'>
    $(function() {
        $("#modal").dialog({ title: "It works" })
    });
  </script>
</head>
 
<body>
<div id='modal'>jQuery UI!</div>
</body>
 
</html>

As a bonus, here is the markup in jsbin.

DevTools Feature Request – console.scope()

Wednesday, September 12th, 2012

Sometimes I just want to see all (or many) of the variables inside of the function, and it can be a bit of work to copy all of the variables into the console.log() call when you know that you are just going to delete the line afterwards anyway.

It would be great to have a console function that handles this. It would be called console.scope. When you call console.scope() it would act similarly to console.trace(), except instead of seeing the call stack in the console, you would see the same thing that you see in the ‘Scope Variables’ panel when inside a breakpoint in the Sources Panel (see images).

I have also opened a thread about this on the devtools mailing list.

TinyColor On npm

Wednesday, September 12th, 2012

I have published my TinyColor package to the npm repository – https://npmjs.org/package/tinycolor2. Unfortunately it is called tinycolor2 since tinycolor was already taken.

After running

npm install tinycolor2

You can use tinycolor like so:

var tinycolor = require("./tinycolor");
console.log(tinycolor("red").toHex());

See the project homepage or the README for more info.

DevTools Feature Request: Show Stack Trace In Event Listeners

Thursday, June 21st, 2012

I was asked a question in my DevTools talk at ComoRichWeb this month.

Q: How do the event listeners work when the events are bound with jQuery?

A: Not well. I rarely use that section when using a framework to bind events, because the event listeners never point back to the actual function being bound – instead they link to the jQuery source.

The info you see on event listeners bound with jQuery is not very useful. It shows you the actual function where the events were bound (which is inside of the jQuery source).

Open up this simple event listener test case in devtools (inspect the button and view event listeners) to see what I mean.

What Information Do You Want From Event Listeners?

What I am actually interested in is the actual callback that jQuery is adding. Of course devtools shouldn’t have to handle jQuery (or other frameworks) specifically, but what if it showed the callstack that caused the event to be bound?

So, by setting a breakpoint to the actual event event binding, here is what I got. This is what I am actually interested in:

Solution?

And putting my photo editing skills to the test, here is what it could look like (of course, this should be styled consistently). Clicking on one of the entries in the callstack would take you into the relevant place in the scripts panel.

This would be ideal. Is this even possible? Or there is an existing or better way to get around this that I don’t know about?

DevTools Talk – Slides and Links

Thursday, June 21st, 2012

I presented on using Chrome Developer Tools at ComoRichWeb, a web developer user group in Columbia, MO on June 20th. Here are the slides and some other links:

Slides and Demo

Other Links Mentioned in the Talk

We had a good turnout last night, was glad to get a chance to share some front-end development tips with local developers.

FileReaderSync

Friday, June 1st, 2012

I have been working on updating the FileReader.js JavaScript file reading library lately to help out with a few different projects. This library has provided a quick way to get started with reading files on a few different projects, like mothereffinganimatedgif.com and Instant Sprite.

One thing I noticed was that there is a FileReaderSync API, meant for loading files synchronously.

You might wonder why on earth would you want to load a file synchronously in your browser – that seems like it could block the entire UI until the file is loaded! It turns out you can’t, at least not in the normal window context. FileReaderSync only exists inside of the context of a WebWorker:

Implementation

View a A working JS Fiddle using FileReaderSync.

I also wrote about how to load web workers without a JavaScript file, but this technique works just fine using a normal external reference.

markup

<input type='file' id='files' multiple onchange='handleFileSelect()' />

page javascript

function processFiles(files, cb) {
    var syncWorker = new Worker('worker.js');
    syncWorker.onmessage = function(e) {
        cb(e.data.result);
    };
 
    Array.prototype.forEach.call(files, function(file) {
        syncWorker.postMessage(file);
    });
}
 
function handleFileSelect() {
    var files = document.getElementById('files').files;
    processFiles(files, function(src) {
        var img = new Image();
        img.src = src;
        document.body.appendChild(img);
    });
}

worker.js

self.addEventListener('message', function(e) { 
    var data=e.data; 
    try { 
        var reader = new FileReaderSync(); 
        postMessage({ 
            result: reader.readAsDataURL(data)
        });
   } catch(e){ 
        postMessage({ 
            result:'error'
        }); 
   } 
}, false);

The jsFiddle demo is a little more complicated than this, since it handles checking for support and an inline worker.

Gotchas

Something that was a little weird is that since you can’t detect support from the main window, I need to spawn off a worker to post the message of whether it supports FileReaderSync. See a jsFiddle to detect FileReaderSync support. There may be a better way to do this, but I don’t know of it.

This can be pretty complicated, but I have been tying it all into the filereader.js plugin, to make reading with FileReaderSync just an option along with the standard FileReader

Performance

It’s hard for me to accurately measure the performance. On one hand, the FileReaderSync seems to load the images in a slower time per image (measured in milliseconds). I assume that this is due to the overhead and message passing with the worker, or possibly because it is a newer implementation.

However, on large images and videos, it definitely feels like the UI does not lock up as much when processing the files.

Purpose

I feel like maybe part of the point of this API is when you want to some heavy lifting with the file after it is loaded but still inside the worker, which isn’t currently supported in FileReader.js. I could imagine ways this use case could be supported though (maybe by passing in a process() function as a string that the worker could call?

Check out the FileReader.js demo and see if you can tell a difference! I’d love to get any kinks worked out and get some feedback – I have been thinking of setting up a js-file-boilerplate project on Github to tie together a bunch of this functionality in a sample project.

Load Web Workers Without A JavaScript File

Friday, May 25th, 2012

Ever want to load a JavaScript Web Worker without specifying an external JavaScript file? There are a couple of different ways to do this by creating a blog and object URL – I wrapped this functionality up into a little plugin to share.

Here is the code. Or checkout out a working jsfiddle demo

 
var WorkerHelper = (function() {
 
    var BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder;
    var URL = window.URL || window.webkitURL;
 
    function getURL (script) {
        if (window.Worker && BlobBuilder && URL) {
            var bb = new BlobBuilder();
            bb.append(script);
            return URL.createObjectURL(bb.getBlob());
        }
 
        return null;
    };
 
    function getWorker (script, onmessage) {
        var url = getURL(script);
        if (url) {
            var worker = new Worker(url);
            worker.onmessage = onmessage;
            return worker;
        }
 
        return null;
    };
 
    return {
        getURL: getURL,
        getWorker: getWorker     
    }
 
})();
 
<div id='log'></div>
 
<script type='text/worker' id='worker-script'>
    self.addEventListener('message', function(e) { 
        postMessage(e.data / 2); 
    },false);
</script>​
 
<script type='text/javascript'>
 
// Load a worker from a string, and manually initialize the worker
var inlineWorkerURL = WorkerHelper.getURL(
    "self.addEventListener('message', function(e) { postMessage(e.data * 2); } ,false);"
);
var inlineWorker = new Worker(inlineWorkerURL);
inlineWorker.onmessage = function(e) {
    document.getElementById('log').innerHTML += '<br />Inline: ' + e.data;
};
 
 
// Load a worker from a script of type=text/worker, and use the getWorker helper
var scriptTagWorker = WorkerHelper.getWorker(
    document.getElementById('worker-script').textContent,
    function(e) {
        document.getElementById('log').innerHTML += '<br />Script Tag: ' + e.data;
    }
);
 
inlineWorker.postMessage(1);
inlineWorker.postMessage(2);
inlineWorker.postMessage(100);
scriptTagWorker.postMessage(1);
scriptTagWorker.postMessage(2);
scriptTagWorker.postMessage(100);
 
</script>

Astar Graph Search – Variable Costs

Tuesday, May 8th, 2012

I’ve been working on updating my A* Graph Search Algorithm (A* on Github) and toying with the idea of adding variable costs to the grid, also known as weighted paths.

I opened an issue to add weighting to graph nodes a while ago, but am a little stuck on the implementation details. My initial thought was to change the semantics of the graph. Right now, here is a sample graph:

 
var GraphNodeType = { 
    OPEN: 0, 
    WALL: 1 
};
 
// 0 represents an open node, 1 represents a wall 
var graph = new Graph([
    [0,0,0,0],
    [1,0,0,1],
    [1,1,0,0]
]);

My initial plan for adding weighting was something like this:

 
var GraphNodeType = { 
    WALL: 0,
};
 
// Anything > 0 represents the cost to travel to that node, 0 represents a wall
var graph = new Graph([
    [2,1,3,4],
    [0,1,1,0],
    [0,0,3,10]
]);

One major issue with that is that it breaks backwards compatibility with the plugin. A user, spellfork, on the Github issue came up with a neat solution, basically passing in two separate arrays to the graph function, where one represents the “obstacle map” (walls), and the second represents the “terrain map” (costs).

 
// First array: 0 represents an open node, 1 represents a wall 
// Second array: movement costs are represented by numeric value 
var graph = new Graph([
    [0,0,0,0],
    [1,0,0,1],
    [1,1,0,0]
],[
    [2,1,3,4],
    [0,1,1,0],
    [0,0,3,10]
]);

This is nice because the terrain map is optional, but not as nice if you need to do a lot of work to generate the two separate maps.

Maybe there is a better solution that I am not thinking of? Any ideas about the best way to implement this? Drop a comment here or over in the Github issue to help get this implemented!