When building up a Wordpress site, the first thing a web developer wants to do is to add some JavaScript to his/her template to bring pages to life. This is one of the most common errors when dealing with JavaScript and Wordpress. First of all, behavior is the last thing you need to add to your pages. First comes the structure, then presentation and only later behavior. If you don't stick to this separation, you will probably stumble on some weird behavior by browsers. In this post I'm going to show you how to debug your scripts within a Wordpress set up.
Syntax errors
Syntax errors happen. Either because you don't remember the exact name of a method or property or because you makes typos, these kind of errors are surely the most common. As a rule of thumb, you should break your scripts into logical parts and then test them separately. There's nothing worse than writing 100 lines of code, testing everything just to find out that your browser returns a long list of errors. This is due to the fact that you didn't break your code into logical parts. For example:
var Class = { property: 'Test', method: function() { return Class.property; } property2: 'Test2' };
Here there's a syntax error because the above object lacks of a comma after the first method. This object contains just a few lines of code, but there are many cases where such an object contains a long list of methods and properties. In short: to deal with this kind of errors, break down your code into little sections, test them and only then keep on writing other code.
DOM errors
DOM errors occur either when you're trying to retrieve an element that doesn't exist or when you're trying to modifying a DOM structure. A typical example is the case of the getElementById()
and getElementsByTagName()
methods. While the former returns null
when an element doesn't exist, the latter fails silently without returning any error. To deal with this behavior, you should run some tests:
var element; if(document.getElementById('test') !== null) { element = document.getElementById('test'); } var elements = document.getElementsByTagName('p'); if(elements.length > 0) { // do something }
As you can see, a couple of preliminary tests have been made just before executing the rest of our code. You should always run this kind of tests when working with the DOM.
Loading libraries and plugins
When loading libraries and plugins, bear in mind the following order:
- the main library
- the plugin
- your custom scripts
For example:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <script type="text/javascript" src="wp-content/themes/theme/js/jquery.color.js"></script> <script type="text/javascript" src="wp-content/themes/theme/js/myScript.js"></script>
If you do not follow this order, browsers will return many errors saying, for example, that one or more objects are undefined
.