Jay Hoffmann

Books, movies, and code


First Steps with Javascript and WordPress

It starts with a simple maxim.

Learn Javascript Deeply.

That’s what Matt said. And it’s good advice. Javascript underpins everything we do, and it’s becoming more and more advanced every day. It’s not just the future of WordPress, it’s the future (and present) of the web.

Of course, Matt mentioned this right around the time he showed off a new admin dashboard written entirely in client-side Javascript with React, and proxied through a server also written in Javascript. Which is great for WordPress. But it’s not a great place for everyone to start.

The truth is there are a number of ways to start using Javascript that are a little more… approachable. My goal here is to go through a few ways you can start using Javascript, today, without completely changing your workflow.

I will be talking about a lot of things. There will be code. I won’t be diving too deep into any one thing. My hope is that I can spark some interest for you. That you connect with one of these new processes or patterns and you feel encouraged enough to keep digging.

Generally speaking, I think there are three great ways to approach Javascript.

  • Using Javascript to manage a front-end build process
  • Managing events, page transitions and AJAX with a watchful eye
  • Building a full-scale Single Page Application with the WordPress REST API.

I want to talk about that last bit a lot more in the future. But for now, I’m mostly going to focus on the first two.

Javascript Build Tools

If you develop front-end code in your plugins or themes, you’ve probably noticed yourself doing the same things over and over. Things like compiling SASS down to CSS, concatenating JS files together and minifying them, creating SVG or icon fonts, linting your code for errors, the list goes on You might have even heard of some nifty tools out there like CodeKit or Prepross that can do this for you. But there’s another way you can do this. With Javascript.

Javascript build tools allow you to create basic script files that will automatically perform these tasks for you, with a little help from Node on the command line. Build tools are a great way to learn Javascript because the barrier to entry and the risk factor can’t be lower. If you screw up, it won’t effect your live site. You’ll just have to track down the error and try again.

These build tools typically run on top of Node, which is why you’re able to run it from your machine. And there are a lot of them out there. I’m just going to focus on two: Grunt and Gulp.

Since both use Node, they follow the same basic procedure.

  1. Install NodeJS, either from the site or with a tool like Homebrew
  2. Navigate to your theme or plugin folder in your Terminal and type one command: npm init. This will automatically create a file called package.json. This stores a list of dependencies that the build tool will need to work. But don’t worry, you won’t be editing this file directly.
  3. The way you do add packages is with npm install PACKAGENAME --save-dev. These packages will automatically get added to your package.json file for future use.
  4. Create a Gruntfile or Gulpfile (depending on your preference)

I’ll start with Grunt. Grunt works by creating basic Javascript objects, which you use to pass in configurations for modules. There’s not a whole lot too it, but you can chain them together to do some pretty great stuff. For instance, if we wanted to concatenate our JS files and compile SASS files, we would install packages with npm install grunt-contrib-concat grunt-contrib-sass --save-dev. Then we would set up our Javascript in a file called Gruntfile.js.

Gruntfile.js

[snippet slug=gruntfile-ultra-simple-example lang=js]

One thing that you’ll learn about in Javascript is that just about everything is an object. That means that inside of these objects you can run any Javascript you want. So you can take grunt files, put them next to vanilla Javascript functions or variables and build anything. The possibilities are really endless.

Gulp is similar, with a few small differences. It works by chaining together tasks, one after another. It also uses CommonJS, so if you’re looking to learn more about Javascript modules and how to link together small packages, it may be a good starting point. To run the same tasks we have in the Grunt example, we just install our packages with npm install gulp-sass gulp-concat --save-dev, and then add our Gulpfile.js.

Gulpfile.js

[snippet slug=gulpfile-ultra-simple-example lang=js]

Interested?

Organizing Javascript

But you can do even more with Javascript. It turns out that a lot can be learned simply from structuring your Javascript better.

If you’ve been coding up themes or plugins for a while, chances are you’ve written some jQuery. You know, click this button to show a dropdown type stuff. And you’ve probably written out code that looks like this:


$('.btn-thing').on('click', function(e) {
    // Do your stuff
});

But there’s a better way. Learn yourself a few basic Javascript patterns to manage your events, and you’ll find yourself writing reusable code over and over.

The Module Pattern

The module pattern can be a great way to organize events like clicks, input changes, or other basic jQuery binded events. Remember how I said everything in Javascript is an object? Well the Module pattern uses this as an advantage. You basically store all of your events in a single object, decoupling your elements from the functions that is called when an event occurs. This is probably easiest to explain with some code:

The Module Pattern

[snippet slug=the-module-pattern lang=js]

Elements are stored in the “el” objects, events are controlled from the init function, which then passes the buck down to individual functions. Writing code like this makes things a lot easier to read, and it can make your job easier.

The Inheritance Pattern

If you wanted to take this a step further, the Inheritance pattern may do the trick. It starts out the same way, you build a simple object which sets up some basic functionality. But you also include a way to extend that object, so you can pass it a few options that will change functionality.

This is most commonly seen in jQuery plugins, but there’s no reason why you can’t start doing this today. That way, you don’t have to keep writing the same functionality over and over again. Instead you write it once, and then just pass an object a few options to change little things here and there. Then your code becomes a reusable module.

The Inheritance Pattern

[snippet slug=the-inheritance-pattern lang=js]

There are really two things to pay attention to here. The $.extend({}) function is what extracts options out to use within the main object. And the $.inherit() function is what will pass options back up to the Object when something is called.

Interested?

Managing AJAX and Page Transitions

AJAX stands for Asynchronous Javascript and XML. In practice, it means fetching chunks of HTML or data using Javascript and loading it into a page without a page refresh. Coupled with some new HTML5 features and Javascript libraries, AJAX can really add to your site. It can make screens transition from one to the next, as a user navigates seamlessly around your site.

There are lots of ways to manage AJAX in WordPress. But the way I prefer is to organize the server-side code into a single Class and then use the module pattern to interpret the requests. Rather then try to explain that all here, I’ll let Jay Wood over at WebDev Studios do it for me. Really, click that link. It’s a great article.

I will, however, mention two Javascript libraries of interest: smoothState.js and pjax.

Both libraries automatically fetch pages when a user clicks on any links and loads the content in. smoothState puts more of an emphasis on the transitions between pages, using CSS3 transitions and basic class switching to do most of the work. To set it up you just need a simple object.

smoothState

[snippet slug=smoothstate lang=js]

pjax is even simpler to get started with, but can do a bit more if you dive in. To automatically start pulling in content without a page refresh you just need to load the code and write one line of Javascript.

$(document).pjax('a', '#pjax-container');

But there’s a lot more that can be done. Exploring the library and employing some of the patterns talked about earlier can go a long way. But check out the links below for some great implementations.

Interested?

The REST API and Beyond

The big news for WordPress this year was the REST API. Again, this isn’t the time to go too deep into this, but basically the REST API allows you to access your site’s content as basic data JSON objects. These data objects can be read by frameworks like Backbone, Angular and React to process content completely on the client-side (on the browser). This allows you to build more complex web applications instead of just sites. Think Gmail. Or Facebook.

And that’s just scratching the surface of the REST API. It can also be used to connect to third party platforms and services, and even more importantly I think, get sites talking to each other. Which is really cool. And will almost certainly require some Javascript. So roll up your sleeves, find your entry point, and get going.

Interested?

Just Keep Learning

I’m hoping I peeked your interest somewhere. I’m hoping you’re ready to learn Javascript and have some resources to get started with. The trick is to start somewhere, get familiar and keep the ball rolling.



One response to “First Steps with Javascript and WordPress”

  1. Lars Steffensen Avatar

    I am slowly driven to the conclusion that all developers are idiots.

    You start with good intentions: Writing something for those that want to take their first steps into javascript coding for wordpress. There should be a few billion people like that. And since you rank well for searches related to that, quite a few will read your post.

    You also give a few more hints about “…a great place for everyone to start” and “…ways you can start using Javascript”.

    But instead of following up on that you jump to “Build Tools”, compiling SASS, concatenating JS files together and minifying them, creating SVG or icon fonts…I wont go on, but it gets worse.

    What happened to the good intentions about talking to people who would like to start using javascript coding? Why cant you make any suggestions that seem fitting? You dont care? You cant write? You dont know what beginners need? You want people to forget about your site asap? Did you ever talk to anyone who fits your usecase?