Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Thursday, April 2, 2015

An Article With Browserify Impressions

This is an opinionated article that discusses Browserify and compares it to RequireJS and Bower.

What is Browserify?

Browserify brings Node.js's require() function to client-side JavaScript. You can call require(...) to import npm packages, so Browserify solves two problems:
  1. Client-side package management (by using npm)
  2. Loading modules

Benefits of Using Browserify

Browserify has some 'magic' built-in that allows you to easily re-use most server-side code in your client-side code.

Because npm handles package management for Browserify, you can specify (most) of your client-side dependencies in your package.json along with your server-side dependencies. In my experience, having one place for dependencies really simplifies the process of adding a new dependency. Otherwise, you have to choose which package manager you want to use for packages that are available through multiple managers.


Problems With Alternatives

Like everything in JavaScript development, there are alternatives to Browserify. RequireJS can be used to load modules. For client-side package management, there's Bower. Either solution has problems that would be reduced or eliminated by using Browserify instead.

RequireJS requires using RequireJS modules or shims. Jam provides packages for RequireJS, but I found extremely out-of-date packages for popular libraries like Moment.js and Modernizr. For the most part, using RequireJS with popular client-side libraries means using shims. RequireJS shims can lead to a few minor problems as you either have to copy & paste JS files into your project or split dependencies into multiple specification files. Browserify shares this problem with RequireJS, but it's a smaller problem for reasons described below.

Bower has some problems of its own. I'll explain, but I must warn you ahead of time: friends and family of Bower should skip to 'Problems with Browserify.'

Bower is an incomplete package management solution. Every Bower package that I have ever installed dumps the complete contents of a Git repository into a directory. And there does not seem to be a standard for Bower package structure or documentation or use in client-side applications.

Every time I use a Bower package, I'm left wondering how to actually use the package in my code. I feel that this is a massive issue that prevents Bower from being as useful as it could be. npm and Browserify typically do not suffer from this problem for a few reasons:
  • npm packages almost always tell you how to start using the package
  • You typically don't need to know the structure of npm packages due to how they're used.
  • If you need to look in the node_modules folder, packages typically use a standard structure.

Problems With Browserify

Browersify is a full solution, but it comes with problems of its own.

It's unclear what npm package should be used for some client-side libraries. Modernizr has a few npm packages: browsernizr, modernizr, and browsernizr2. The first package is outdated, and the second package installs a tool that generates modernizr.js. I only found out about the third package as I was doing research for this article, and I don't know anything about it except its existence.

If a library doesn't have an easy-to-use npm package, you have to shim it with browserify-shim. This complicates inclusion of client-side vendor scripts in your project, and Browserify shares this issue with with RequireJS. Unlike RequireJS, this problem should be uncommon due to the availability of npm modules for popular client-side libraries.

Addendum: Comparison of Browserify and RequireJS

Browserify and RequireJS solve most of the same problems, so I figured that now would be a good time to give a quick rundown of differences and similarities.

Differences

Browserify loads npm modules.
RequireJS loads RequireJS modules.

Browserify always loads synchronously at compile/bundle time.
RequireJS loads asynchronously in the browser (but can be bundled using an optimizer).

Browserify always bundles scripts.
Bundling RequireJS apps requires a special optimizer.

Browserify uses npm.
RequireJS can be used with Jam, but you may be better off with using shims for third-party code.

Browserify allows you to access many Node.js functions and modules from client-side code.

RequireJS allows you to load non-JavaScript files (such as text files and Ember.js templates).

Similarities

Both load modules for client-side JavaScript.
Both have Grunt and Gulp plugins.

Sunday, August 24, 2014

RequireJS Impressions

RequireJS is a JavaScript library for defining and loading modules. It provides an alternative to including multiple <script> tags in your HTML in the right order and defining countless global variables (or properties for global variables.)

I've been using it quite a bit lately, so I have some opinions about it.

Good News

I like that RequireJS works with many browsers. The official site claims compatibility with ancient versions of every major browser. And have you seen its source code? A piece at the top checks to see if it's running on the Playstation 3's browser and does a little workaround just for it. I get the impression that RequireJS will work on anything that one would need it to, and that's a very good thing when you're building web sites that need to work everywhere.

"Ehhh..." News

Module names are case-sensitive. If you get the case wrong, RequireJS will happily reload modules. If those reloaded modules do anything to global state, you're heading for headache.

I could find only one bundling tool that properly bundles RequireJS modules together: the optimizer (r.js) that comes with RequireJS. This tool has "experimental support for source maps" (source: RequireJS Docs - Source Maps), so not using source maps poses two problems:
  1. Serving individual files for development and optimized files for production
  2. Actually using those files in each environment
Solving both of these problems can get tricky, especially in the ASP .NET MVC 4 environment that I've been working with. The easier of the two problems is the first: force the asset pipeline to use the output of r.js instead of its own optimized output. Easier said than done, but it's not impossible.

The second problem, actually using the files, is difficult and gets interesting when you're to use the application cache. One solution that I came up with is absolutely terrible and I will not be sharing it because it's wrong in so many ways. But I came up with it because there isn't much documentation available for taking full advantage of RequireJS's optimizer. Currently, it's a few sparse details and a (non-working) configuration file they put up on GitHub. This documentation could use some serious improvement.

These warts, while major, won't stop me from using RequireJS. It provides worthwhile functionality to client-side JavaScript. Browserify seems like a worthwhile replacement that fixes many of my RequireJS gripes, but I haven't used it yet and its compatibility is not as good as RequireJS's.

Saturday, July 12, 2014

jQuery Color & Body Background-Color WebKit Bug

jQuery Color is a nice jQuery plugin that allows you to animate color changes and much more. When testing a project that I was working on in Chrome (on Windows and Mac), I stumbled on a weird graphics glitch that occurs when animating a background color change for the entire page.

(Screenshot taken from latest Chrome for Windows)
See the light grey stripe at the bottom? It's supposed to be the same color as the rest of the page.

As far as I know, this is not a jQuery Color bug but rather a WebKit issue because it also affects Safari on Mac.

There are quite a few workarounds.

Fix #1 - Force redraw in animation done handler


The accepted answer is very simple; it's just three lines of JavaScript and doesn't require jQuery.

Using this fix with the entire body presented a problem with my project. These rapid changes to display make the page behave like it's scrolling back to the top.

Fix #2 - Apply two-thirds of clearfix to empty div/footer

My instincts told me to add an empty <footer /> to the bottom of the screen and give it clearfix styling. Clearfix corrects this bug. You can actually use two-thirds of a certain recommended clearfix:

footer:after {
    content:"";
    display: table;
}

(It's missing clear:both;)

<footer /> can be changed to <div /> or any number of other elements.

Fix #3 - Apply two-thirds of clearfix to body

Adding an empty HTML element seems like a bad idea to me. HTML5 is supposed to be about content, and here I am adding an element just to fix a browser-specific presentation bug.

As it turns out, you can use this bit of CSS and skip the empty footer:
body:after {
    content: "";
    display: table;
}

I don't know why this works

Maybe I'll update this post later when I figure it out.

Friday, August 23, 2013

Using AngularJS with Bootstrap Form Validation

If you are using AngularJS with Bootstrap (formerly Twitter Bootstrap), you will want to use AngularJS's form validation with Bootstrap's form classes. This can be surprisingly tricky and requires careful use of AngularJS's ngClass directive.

This is best illustrated with sample markup. It's extracted from a project that I'm working on:


The general idea behind this is that you need to set Bootstrap's 'has-error' class when loginForm's email field is invalid. Simple enough, right?

AngularJS introduces two issues that are present in the latest unstable version (1.2.0rc1). They could be in previous versions, but I didn't check.
  1. You must have quote marks around the name of the 'has-error' class in the ng-class expression.
  2. The input must be bound to the model by using AngularJS's ngModel directive
If you just put ng-class='{has-error: loginForm.email.$invalid}' your JS will crash within AngularJS because it's an invalid expression.

I have little idea why data binding is required. I suspect that AngularJS requires it because it expects you to use the field's contents somewhere else in your app.

Saturday, May 11, 2013

Freezing jQuery NuGet Package Version

jQuery v2.0.0 was released last month, and it does not support Internet Explorer 6/7/8. If you use NuGet to include jQuery in your .NET projects, your jQuery files might be updated to this latest version without old IE compatibility. You can force NuGet to keep v1.9.1 when you update your solution's packages, but you have to manually edit the package file for each project with jQuery.

A project's packages.config file can be found in the root directory of that project (where the .proj file is). Open each packages.config file and look for a line similar to this one:


<package id="jQuery"
            version="1.9.1" 
            targetFramework="net40" />

(The targetFramework attribute may be different)

Adding an allowedVersions attribute allows you to control what version will be used by NuGet during updates. Here's an example:

<package id="jQuery"
            version="1.9.1"
            allowedVersions="[1,2)"
            targetFramework="net40" />
allowedVersions="[1,2)" tells NuGet to grab the newest version that falls between v1.0 and v2.0 (excluding v2). This will likely be v1.9.1, the most current version before v2.0.0.

For more information on NuGet versioning, please go to NuGet versioning documentation.

Thursday, March 21, 2013

I Like AngularJS (So Far)

I am building a commercial web app using AngularJS that is currently around 3000 lines of JavaScript code (including comments and spacing). I like AngularJS and I'll tell you why.


Wednesday, December 26, 2012

ServiceStack and jQuery Problems

I'm currently working on a website that uses ServiceStack, and I ran into a problem where complex request objects were not properly created when making requests in-browser using jQuery. Simple (flat) requests worked as expected, but complex requests (with nested objects) led to various null-related errors coming from the service implementation. My unit tests worked fine, but I could not access the 'complex' service within a web browser.

My problem seemed to be with my client-side JavaScript code. I was writing code similar to the following:

// Bad example - DO NOT FOLLOW
$.ajax({
    url: '/url/',
    data: { 'Data': properties },
    type: 'PUT'
}).fail(function() { alert('Oh no'); });

I changed a few lines of code, and everything began working as expected.


// Better example - could probably do better
$.ajax({
    url: '/url/',
    data: JSON.stringify({ 'Data': properties }),
    contentType: 'application/json',
    type: 'PUT'
}).fail(function() { alert('Oh no'); });

This version of the AJAX call specifies content type and uses a JSON string for the data.

According to the jQuery documentation for the ajax function, the default content type is ''application/x-www-form-urlencoded; charset=UTF-8". This default is inappropriate for this particular use case.

The call to JSON.stringify is also important because jQuery's .ajax() function does not convert the data for you.