A fitVids vanilla JavaScript do-over

FitVids.js is a jQuery plugin used to create fluid videos. It helps makes video embeds from YouTube, Vimeo and a number of other sources display nicely on responsive sites.

FitVids calculates the ratio of a video, wraps it in a div and sets the padding to enforce a ratio. A typical 4:3 YouTube embed starts as:

<iframe 
  width="420" height="315" 
  src="//www.youtube.com/embed/btPJPFnesV4" 
  frameborder="0" allowfullscreen></iframe>

Vendor prefixes, polyfills and former clients

Jeremy Keith’s recent post Polyfills and products asked an interesting question about handing polyfilled code to clients:

[Short term client projects] makes it very tricky to include a polyfill in our deliverables. We’d need to figure out a way of also including a timeline for revisiting that polyfill and evaluating when it’s time to drop it.

Open site redesign using a pattern library

As I’ve mentioned previously, I’m in the process of redesigning this web site. It’s very much a work in progress.

Pattern Library

As a first step I’m building a pattern library and I’ve decided to open source the repo during the build process. I’m using Pattern Lab for the purpose.

Optimising the Typekit Code

The Typekit kit editor provides two versions of the embed code, the default version blocks rendering and the asynchronous version which can produce a flash of unstyled content (FOUC).

In the case of Typekit, I prefer the FOUC over slowing down rendering. The asynchronous code also offers the advantage of your site staying online should Typekit go down.

I decided to spend a little time optimising the asynchronous code Typekit provides.

HTML5: I couldn’t (quite) do it

For most of my career as a web developer I’ve produced websites that work without JavaScript. For the JavaScript impaired the sites may be missing a minor visual feature or be a little clunky in places, but they work and the meaning remains clear. It doesn’t bother me that, sometimes, the cost of allowing for sites to load without JavaScript can mean missing out on the latest web fashion. I’m not a big fan of fashion.

Currently, web development is undergoing some major transitions: the HTML5 spec is being developed and CSS3 is being implemented. The browser wars have returned, although this time around, it’s a battle to win developers’ hearts by implementing the newest standards.

Now is the time for developers to re-evaluate their past practices; moving on from the old and embracing the new. I kept that ethos in mind when upgrading the Soupgiant WordPress base theme recently. Among other things we were porting it to HTML5.

JavaScript Localisation in WordPress

Recently on Twitter @iamcracks asked

Attention WordPress Wizards & Gurus. Is it possible to “get WordPress to write a custom field into a javascript variable”?

source

While I wouldn’t be so bold as to claim I’m either a wizard or a guru, I happen to know the answer to @iamcracks question.

A while back I wrote a two part tutorial on using JavaScript the WordPress way, the code below builds on that. The first step is to load the JavaScript in functions.php using wp_enqueue_script() as detailed in the earlier tutorial:

<?php
function brt_load_scripts() {
  if (!is_admin()) {
    wp_enqueue_script(
      'brt-sample-script', //handle
      '/path/2/script.js', //source
      null, //no dependancies
      '1.0.1', //version
      true //load in html footer
    );
  }
}

add_action('wp_print_scripts', 'brt_load_scripts');
?>

This outputs the html required for the JavaScript when wp_footer() is called in footer.php

Localising the script is done using the function wp_localize_script() it takes three variables:

  • $handle – (string) the handle defined when registering the script with wp_enqueue_script
  • $javascriptObject – (string) name of the JavaScript object that contains the passed variables.
  • $variables – (array) the variables to be passed

To pass the site’s home page and the theme directory, we’d add this function call below the wp_enqueue_script call above:

<?php
...
wp_localize_script('brt-sample-script', 'brtSampleVars', array(
  'url' => get_bloginfo('url'),
  'theme_dir' => get_bloginfo('stylesheet_directory')
  )
);
...
?>

The output html would be:

<script type='text/javascript'>
/* <![CDATA[ */
var brtSampleVars = {
  url: "http://bigredtin.com",
  theme_dir: "http://bigredtin.com/wp-content/themes/bigredtin"
};
/* ]]> */
</script>
<script type='text/javascript' src='/path/2/script.js?ver=1.0.1'></script>

Accessing the variables within JavaScript is done using the standard dot notation, for example brtSampleVars.theme_dir to access the theme directory.

Using a post’s custom fields is slightly more complicated so I’ll write out the code in full:

<?php
function brt_load_scripts() {
  if (is_singular()) {
    wp_enqueue_script(
      'brt-sample-script', //handle
      '/path/2/script.js', //source
      null, //no dependancies
      '1.0.1', //version
      true //load in html footer
    );

    the_post();
    $allPostMeta = get_post_custom();
    wp_localize_script('brt-sample-script', 'brtSampleVars',
    array(
      'petersTwitter' => $allPostMeta['myTwitter'][0],
      'joshsTwitter' => $allPostMeta['joshsTwitter'][0]
      )
    );
    rewind_posts();
  }
}

add_action('wp_print_scripts', 'brt_load_scripts');
?>

Only pages and posts have custom fields so the check at the start of the function has become is_singlular() to check the user is on either a post or a page, earlier we were testing if the user was anywhere on the front end. The arguments for wp_enqueue_script have not changed.

the_post() needs to be called to start the loop and initiate the $post object so the associated custom fields can be accessed in the following line and put in an array.

With the custom fields easily available, the information can then be passed to wp_localize_script() as earlier demonstrated. The final step is to rewind the loop so next time the_post() is called, from either single.php or page.php, the post data is available.

The html output from the sample above would be:

<script type='text/javascript'>
/* <![CDATA[ */
var brtSampleVars = {
  petersTwitter: "@pwcc",
  joshsTwitter: "@sealfur"
};
/* ]]> */
</script>
<script type='text/javascript' src='/path/2/script.js?ver=1.0.1'></script>

JavaScript the WordPress Way / Part 2

In Part 1 we discussed the conflicts that can occur on a WordPress site if themes and plugins add JavaScript using <script> tags. We introduced the wp_register_script and wp_enqueue_script functions developed to avoid these conflicts.

In this section we’ll deal with a more complicated example and use Google’s AJAX libraries API to lower your bandwidth costs. We’ll also take what we’ve learnt about including JavaScript and apply it to our CSS.