<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Big Red Tin &#187; plugin</title>
	<atom:link href="http://bigredtin.com/tag/plugin/feed/" rel="self" type="application/rss+xml" />
	<link>http://bigredtin.com</link>
	<description>Thoughts about the web and business from the large pantry</description>
	<lastBuildDate>Wed, 08 Feb 2012 06:55:38 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
<xhtml:meta xmlns:xhtml="http://www.w3.org/1999/xhtml" name="robots" content="noindex" />
		<item>
		<title>Delay Print Stylesheets Plugin</title>
		<link>http://bigredtin.com/2010/delay-print-css-plugin/</link>
		<comments>http://bigredtin.com/2010/delay-print-css-plugin/#comments</comments>
		<pubDate>Fri, 27 Aug 2010 02:17:29 +0000</pubDate>
		<dc:creator>Peter Wilson</dc:creator>
				<category><![CDATA[Behind the Websites]]></category>
		<category><![CDATA[CSS]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[plugin]]></category>
		<category><![CDATA[WordPress]]></category>

		<guid isPermaLink="false">http://bigredtin.pressgiant.net/?p=739</guid>
		<description><![CDATA[A few weeks ago I wrote a post in which I adapted an idea from a zOompf article to delay the loading of print stylesheets until after a web page has fully rendered. I've decided to convert the code from the original post into a plugin and add it to the WordPress plugin directory.]]></description>
			<content:encoded><![CDATA[<p>A few weeks ago I wrote a post in which I <a title="adapted an idea from a zOompf article" href="http://bigredtin.com/behind-the-websites/delay-loading-of-print-css/">adapted an idea from a zOompf article</a> to delay the loading of print stylesheets until after a web page has fully rendered. I finished that post with the following point/question:</p>
<blockquote><p>Another question to ask is whether all this is actually worth the effort – even when reduced through automation. On Big Red Tin, the print.css is 595 bytes, the delay in rendering is negligible.</p></blockquote>
<p>Chris and Jeff at <a title="Digging into WordPress" href="http://digwp.com">Digging into WordPress</a> picked up the article and posted it on their site. In turn it was picked up elsewhere and became the surprise hit of the summer at Big Red Tin. Not bad when one is shivering through a bitter Melbourne winter.</p>
<p>As a result of the interest, I decided to convert the code from the original post into a plugin and add it to the WordPress plugin directory.</p>
<h4>Further Testing</h4>
<p>As I warned in the original article, I&#8217;d tested the code in very limited circumstances and found it had worked. Fine for a code sample but not enough for a sub version-1.0-release plugin. Additional testing showed:</p>
<ol>
<li>Stylesheets intended for IE, through conditional comments, were loading in all browsers</li>
<li>When loading multiple stylesheets, the correct order was not maintained in all browsers</li>
</ol>
<p>If jQuery was available I wanted to use it for JavaScript event management otherwise I&#8217;d use purpose-written JavaScript. There&#8217;s no point, after all, of worrying about the rendering delay caused by 600-1000 bytes only to load a 71KB (or 24KB <a title="gzipped" href="http://developer.yahoo.net/blog/archives/2007/07/high_performanc_3.html">gzipped</a>) file in its place.</p>
<p>Other things I wanted to do included:</p>
<ol>
<li>Put the PHP in a class to reduce the risk of clashing function/class names</li>
<li>Put the JavaScript in its own namespace</li>
<li>Keep the output code as small as possible</li>
</ol>
<p>To support conditional comments for IE required adding each stylesheet within a separate &lt;script&gt; tag, using this method the output HTML takes the following form:</p>
<pre><code>&lt;script&gt;
  // add global print.css
&lt;/script&gt;
&lt;!--[if IE 6]&gt;
  &lt;script type='text/javascript'&gt;
    // add ie6 specific print.css
  &lt;/script&gt;
&lt;![endif]--&gt;</code></pre>
<p>This violates my aim to keep output as small as possible but footprint has to take second place to bug-free. I could have translated the code to use <a title="JavaScript conditional comments" href="http://en.wikipedia.org/wiki/Conditional_comment#Conditional_Comment_in_JScript">JavaScript conditional comments</a> by translating the IE version to the JavaScript engine it uses but this could lead to future-proofing problems.</p>
<p>To maintain the order of stylesheets, I added each event to an array of functions and then used a single event to loop through the array of functions. If jQuery is used, I add multiple events because jQuery runs events on a first in first out basis.</p>
<p>Putting the PHP in a class and the JavaScript in its own namespace is fairly self-explanatory. <a href="http://bit.ly/bBUXCh">Google is your friend</a> if you wish to read up further on this.</p>
<p>Minimising the footprint was also a simple step. I wrote the JavaScript out in full with friendly variable names. Once I was happy with the code, I ran the code through <a href="http://refresh-sf.com/yui/">the YUI JavaScript compressor</a>, commented out the original JavaScript in the plugin file and output the compressed version in its place.</p>
<p>The JavaScript is output inline (within the HTML) to avoid additional HTTP requests. I was in two minds about this because browser caching is lost in the process. So it may change in a later version.</p>
<p>I&#8217;ve worked out another way to keep the footprint small. Rather than creating a function to pass the stylesheet&#8217;s URL and ID to <code>brt_print.add(url, id)</code>, I wrote out the full function for each style sheet. I&#8217;ll fix that in the next release.</p>
<p>You can <a title="download" href="http://wordpress.org/extend/plugins/delay-print-css/download/">download</a> the <a title="Delay Print CSS Plugin" href="http://http://wordpress.org/extend/plugins/delay-print-css/">Delay Print CSS Plugin</a> from the WordPress plugin repository.</p>
]]></content:encoded>
			<wfw:commentRss>http://bigredtin.com/2010/delay-print-css-plugin/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Getting the bloginfo correctly</title>
		<link>http://bigredtin.com/2010/getting-the-bloginfo-correctly/</link>
		<comments>http://bigredtin.com/2010/getting-the-bloginfo-correctly/#comments</comments>
		<pubDate>Tue, 13 Jul 2010 02:12:30 +0000</pubDate>
		<dc:creator>Peter Wilson</dc:creator>
				<category><![CDATA[Behind the Websites]]></category>
		<category><![CDATA[bloginfo]]></category>
		<category><![CDATA[coding]]></category>
		<category><![CDATA[domains]]></category>
		<category><![CDATA[plugin]]></category>
		<category><![CDATA[theme]]></category>
		<category><![CDATA[WordPress]]></category>
		<category><![CDATA[WordPress MS]]></category>

		<guid isPermaLink="false">http://bigredtin.pressgiant.net/?p=646</guid>
		<description><![CDATA[One of the standout problems when using plugins with WordPress MS is when they define a constant for the plugin’s url as the script starts executing.]]></description>
			<content:encoded><![CDATA[<p>This site runs on an <a title="WordPress MS" href="http://codex.wordpress.org/Create_A_Network">WordPress </a><abbr title="Multi Site"><a title="WordPress MS" href="http://codex.wordpress.org/Create_A_Network">MS</a></abbr> install, along with a number of other small sites. You can see the full list of sites <a title="on the directory page" href="http://pressgiant.net/">on the directory page</a>.</p>
<p>As with most WordPress sites we use plugins to enhance WordPress, including <a title="Donncha O Caoimh" href="http://ocaoimh.ie/">Donncha O Caoimh</a>&#8216;s excellent <a title="WordPress MU Domain Mapping" href="http://ocaoimh.ie/wordpress-mu-domain-mapping/">WordPress <abbr>MU</abbr> Domain Mapping</a> plugin. As the name implies, the domain mapping plugin allows us to use top level domains for each site rather than being stuck with sub-domains. In the case of this blog, without the plugin it would reside at <a title="bigredtin.pressgiant.com" href="http://bigredtin.pressgiant.net">bigredtin.pressgiant.net</a>.</p>
<h4>Taking care with plugins</h4>
<p>Many plugins are tested for the single site version of WordPress only. I don&#8217;t have a problem with this as most plugins are released under the GPL and free in terms of both speech and beer. If I&#8217;m not paying for software, it&#8217;s up to me to test it in the fringe environment of WordPress <abbr title="Multi Site">MS</abbr>.</p>
<p>Now that WordPress is WordPress <abbr title="Multi Site">MS</abbr> is WordPress, more developers may test in both environments but they certainly can&#8217;t be expected to test with all manner of combinations of plugins.</p>
<h4>The standout problem</h4>
<p>One of the standout problems when using plugins with WordPress <abbr title="Multi Site">MS</abbr> is when they define a constant for the plugin&#8217;s url as the script starts executing, the PHP code may look similar to:</p>
<pre><code>&lt;?php

  define('PLUGIN_DIR', get_bloginfo('url') . "/wp-content/plugins/peters-plugin");

  function plugin_js_css(){
    wp_enqueue_script('plugin-js', PLUGIN_DIR . '/script.js');
    wp_enqueue_style('plugin-css', PLUGIN_DIR . '/style.css');
  }

  add_action('init', 'plugin_js_css');

?&gt;</code></pre>
<p>The above stands equally for themes mapping the stylesheet directory at the start of execution:</p>
<pre><code>&lt;?php

  define('THEME_DIR', get_bloginfo('stylesheet_directory') );

  function theme_js_css(){
    wp_enqueue_script('theme-js', THEME_DIR . '/script.js');
    wp_enqueue_style('theme-css', THEME_DIR . '/style.css');
  }

  add_action('init', 'theme_js_css');

?&gt;</code></pre>
<p>The <a title="get_bloginfo" href="http://codex.wordpress.org/Function_Reference/get_bloginfo"><code>get_bloginfo</code></a> and <a title="bloginfo" href="http://codex.wordpress.org/Function_Reference/bloginfo"><code>bloginfo</code></a> functions return information about your blog and your theme settings including the site&#8217;s home page, the theme&#8217;s directory (as in the second code sample above) or the stylesheet url. <code>bloginfo</code> outputs the requested information to your <abbr>HTML</abbr>, <code>get_bloginfo</code> returns it for use in your <abbr>PHP</abbr>. </p>
<p>Outside of code samples, <code>bloginfo</code> and <code>get_bloginfo</code> are interchangeable throughout this article.</p>
<p>The problems occur when a subsequently loaded plugin needs to change something retrieved from <code>bloginfo</code>. In this site&#8217;s case, Domain Mapping changes all URLs obtained through <code>bloginfo</code>, but it could be a plugin that simply changes the stylesheet url to a subdomain to speed up page load.</p>
<p>In a recent case, a plugin – let&#8217;s call it <a title="Disqus" href="http://disqus.com/">Disqus</a> – was defining a constant in this manner. As result an <abbr title="Cross-site scripting">XSS</abbr> error was occurring when attempting to use Facebook Connect. Replacing the constant with a <code>bloginfo</code> call fixed the problem.</p>
<p>The improved code for the first sample above is:</p>
<pre><code>&lt;?php

  function plugin_js_css(){
    wp_enqueue_script('plugin-js', get_bloginfo('url') . '/wp-content/plugins/peters-plugin/script.js');
    wp_enqueue_style('plugin-css', Pget_bloginfo('url') . '/wp-content/plugins/peters-plugin/style.css');
  }

  add_action('init', 'plugin_js_css');

?&gt;</code></pre>
<h4>bloginfo doesn&#8217;t hit the database everytime</h4>
<p>I presume the developers set their own constants because they&#8217;d like to avoid hitting the database repeatedly to receive the same information.</p>
<p>Having run some tests on my local install of WordPress, I can assure you this is not the case. Running <code>bloginfo('stylesheet_directory')</code> triggers a db call on the first occurrence, the information is then cached for subsequent calls.</p>
<p>I realise I sound incredibly fussy and that I&#8217;m suggesting we protect against edge cases on our edge cases. You&#8217;re right, and <a title="it's not the first time" href="http://bigredtin.com/behind-the-websites/javascript-the-wordpress-way-part-1/">it&#8217;s not the first time</a>, but as developers it&#8217;s the edge cases that we&#8217;re employed to avoid.</p>
]]></content:encoded>
			<wfw:commentRss>http://bigredtin.com/2010/getting-the-bloginfo-correctly/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JavaScript the WordPress Way / Part 2</title>
		<link>http://bigredtin.com/2010/javascript-the-wordpress-way-part-2/</link>
		<comments>http://bigredtin.com/2010/javascript-the-wordpress-way-part-2/#comments</comments>
		<pubDate>Fri, 04 Jun 2010 00:00:20 +0000</pubDate>
		<dc:creator>Peter Wilson</dc:creator>
				<category><![CDATA[Behind the Websites]]></category>
		<category><![CDATA[coding]]></category>
		<category><![CDATA[CSS]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[plugin]]></category>
		<category><![CDATA[theme]]></category>
		<category><![CDATA[WordPress]]></category>
		<category><![CDATA[wp_enqueue_script]]></category>
		<category><![CDATA[wp_enqueue_style]]></category>
		<category><![CDATA[wp_register_script]]></category>
		<category><![CDATA[wp_register_style]]></category>

		<guid isPermaLink="false">http://bigredtin.pressgiant.net/?p=499</guid>
		<description><![CDATA[In Part 1 we introduced the <code>wp_register_script</code> and <code>wp_enqueue_script</code> functions developed to avoid JavaScript conflicts.

In this section we’ll deal with a more complicated example. We’ll also take what we’ve learnt about including JavaScript and apply it to our CSS.]]></description>
			<content:encoded><![CDATA[<p>In <a title="Part 1" href="http://bigredtin.com/behind-the-websites/javascript-the-wordpress-way-part-1/">Part 1</a> we discussed the conflicts that can occur on a WordPress site if themes and plugins add JavaScript using &lt;script&gt; tags. We introduced the <code>wp_register_script</code> and <code>wp_enqueue_script</code> functions developed to avoid these conflicts.</p>
<p>In this section we&#8217;ll deal with a <a title="more complicated example" href="#jswp2complicated">more complicated example</a> and <a title="use Google's AJAX libraries API" href="#jswp2googleapi">use Google&#8217;s AJAX libraries API</a> to lower your bandwidth costs. We&#8217;ll also take what we&#8217;ve learnt about including JavaScript and <a title="apply it to our CSS" href="#jswpcss">apply it to our CSS</a>.<span id="more-499"></span></p>
<h4 id="jswp2complicated">A more complicated example</h4>
<p>The <a title="sample code yesterday" href="http://bigredtin.com/behind-the-websites/javascript-the-wordpress-way-part-1/#jswpregister">sample code yesterday</a> included a simple example of using the same JavaScript file throughout your site. Let&#8217;s spice things up slightly by introducing the following circumstance. Consider that you have three JavaScript files:</p>
<ul>
<li><strong>base.js</strong> is the base JavaScript file to be used throughout the site. It uses the jQuery library and must load in the HTML &lt;head&gt;;</li>
<li><strong>posts.js</strong> loads on pages and posts and only calls functions from the base JavaScript file but doesn&#8217;t use the jQuery library directly. It can load in the HTML footer.</li>
<li><strong>archives.js</strong> loads on all other pages throughout your site (except admin). It calls functions from your base JavaScript file and makes direct use of the jQuery library. It can load in the HTML footer.</li>
</ul>
<p>In this situation, you could change your base.js to use another library – say, Prototype – and it would have no effect on the posts.js. So, posts.js can be said not to depend on jQuery directly.</p>
<p>Changing libraries would require edits to the third file, in which case archives.js does depend on jQuery directly.</p>
<h5>Registering the Files</h5>
<p>The code to register those JavaScript files and conditions with WordPress is:</p>
<pre><code>wp_register_script (
  'mytheme-base', /* handle */
  get_bloginfo('template_url') . '/base.js', /* source */
  array('jquery'), /* requires jQuery */
  1.0 /* version 1.0 */
);

wp_register_script (
  'mytheme-posts', /* handle */
  get_bloginfo('template_url') . '/posts.js', /* source */
  array('mytheme-base'), /* requires base.js */
  1.0, /* version 1.0 */
  true /* load in footer */
);

wp_register_script (
  'mytheme-archives', /* handle */
  get_bloginfo('template_url') . '/archives.js', /* source */
  array('jquery', 'mytheme-base'), /* requires jQuery &amp; base.js */
  1.0, /* version 1.0 */
  true /* load in footer */
);</code></pre>
<p>This code says to WordPress:</p>
<ul>
<li> If loading posts.js, also load base.js;</li>
<li> If loading archives.js, also load jQuery and base.js;</li>
<li> If loading base.js, also load jQuery;</li>
</ul>
<p>Each of these are separate checks (if) rather than a series of options (if, else if).</p>
<h5>Enqueueing the files</h5>
<p>All the hard work has been done registering the files, WordPress knows what each file requires to work and where in the HTML (&lt;head&gt; or footer) the &lt;script&gt; tags should be inserted.</p>
<p>Now it&#8217;s a simple process of checking if the visitor is loading a post or page and requesting the appropriate file.</p>
<p>We need to delay the check slightly, otherwise WordPress won&#8217;t know if the user is on a page, post or elsewhere. The first step is to enclose the check in a function.</p>
<pre><code>function que_scripts(){
  if (!is_admin()) { //visitors only
    if (is_singular()) { // pages &amp; posts
      wp_enqueue_script('mytheme-posts');
    }
    else {
      wp_enqueue_script('mytheme-archives');
    }
  }
}</code></pre>
<p>Then tell WordPress when to execute the function. For this we use the <a title="action" href="http://codex.wordpress.org/Plugin_API#Hooks.2C_Actions_and_Filters">action</a> wp_print_scripts. This runs the code above before WordPress attempts to output the <code>&lt;script&gt;</code> tags to your HTML.</p>
<pre><code>add_action('wp_print_scripts', 'que_scripts')</code></pre>
<p>There is no need to enqueue jQuery or base.js directly. WordPress knows to add those to the HTML based on the dependancies listed when registering the files.</p>
<h4 id="jswp2googleapi">Using the Google AJAX Libraries API</h4>
<p>Loading all these libraries from your own server may seem like a waste of your bandwidth considering you could be loading the libraries directly from Google&#8217;s servers.</p>
<p>With a bit of luck, your visitor will have Google&#8217;s version of the libraries in their browser&#8217;s cache already and <a title="your site will load a little quicker" href="http://bigredtin.com/behind-the-scenes/caching-on-the-google-ajax-libraries-api/">your site will load a little quicker</a>.</p>
<p>It&#8217;s a bit messy to do this yourself, especially since jQuery needs to be kept in noConflict mode. Fortunately <a title="Jason Penny" href="http://jasonpenney.net/">Jason Penny</a> has developed a plugin, called “<a title="Use Google Libraries" href="http://wordpress.org/extend/plugins/use-google-libraries/">Use Google Libraries</a>”, to do the hard work for you.</p>
<p>“Use Google Libraries” is the first plugin I add when setting up sites for me and my clients.</p>
<h4 id="jswp2superfab">Making our super-broken example super-fabulous</h4>
<p>If, when developing their theme and plugin, George and Richard <a title="from our example in Part 1" href="http://bigredtin.com/behind-the-websites/javascript-the-wordpress-way-part-1/#jswpproblem">from our  example in Part 1</a>, had used the <code>wp_register_script</code> and <code>wp_enqueue_script</code> WordPress functions to load their JavaScript, WordPress would know that only one version of jQuery needs to be loaded for both the theme and the plugin to work.</p>
<p>As WordPress releases come in fits and bursts, sometimes the version of the JS libraries included with WordPress fall behind the current version of the library available otherwise.</p>
<p>This is a small price to pay for the knowledge that our sites will remain super-fabulous rather than super-broken, at least when it comes to the JavaScript.</p>
<h4 id="jswpcss">A bonus for CSS</h4>
<p>By now the reasons for using <code>wp_register_script</code> and <code>wp_enqueue_script</code> should be clear. If you want to go that one step further, you can use the equivalent functions for your CSS.</p>
<p>As CSS should always be loaded in the HTML &lt;head&gt;, there is no option to load the CSS files in the footer of the HTML. Otherwise the CSS functions take the same arguments as their JavaScript equivalents. The CSS functions are:</p>
<ul>
<li>wp_register_style</li>
<li>wp_enqueue_style</li>
</ul>
<p>The four parameters they take are:</p>
<dl>
<dt>$handle</dt>
<dd>(required for both functions) Name of the style sheet</dd>
<dt>$source</dt>
<dd>(required for <code>wp_register_style</code>) – URL of the script. Also required by <code>wp_enqueue_style</code> if the style is unregistered.</dd>
<dt>$dependancies</dt>
<dd>(optional) – an array of handles the style sheet depends on</dd>
<dt>$version</dt>
<dd>(optional) – version number</dd>
</dl>
<p>WordPress doesn&#8217;t include any style sheets bases, such as YUI CSS, in the default distribution, so the main purpose of the CSS functions is to allow you to keep track of your version numbers and to call in style sheets only as they&#8217;re needed.</p>
<h4>Conditional comments</h4>
<p>Unfortunately the WordPress functions for JavaScript do not allow for conditional comments, so scripts targeting older versions of IE (okay, I&#8217;m referring to PNG fixers for IE6) need to be coded directly into your theme&#8217;s header.php or footer.php.</p>
<p>On the other hand, the CSS functions do allow for conditional comments, in a round-about fashion. Let&#8217;s register a CSS file we&#8217;ll be targeting at IE6.</p>
<pre><code>wp_register_style (
  'mytheme-ie6', /* handle */
  get_bloginfo('template_url') . '/ie6.css', /* source */
  array('mytheme-css'), /* requires mytheme-css (not shown) */
  1.0 /* version 1.0 */
);</code></pre>
<p>Behind the scenes WordPress is adding the stylesheet to the object $wp_styles. To add the conditional comments you need to access the object more directly. To target the above to IE6, the command is:</p>
<pre><code>$wp_styles-&gt;registered['mytheme-ie6']-&gt;extra['conditional'] = 'IE 6';</code></pre>
<p>If, as in the complicated example above, you need to check where a user is before enqueueing your stylesheet, again you need to enclose the enqueueing command in a function and run it on an action, in this case the action <code>wp_print_styles</code>.</p>
<p>For example, to output the IE6 stylesheet above on pages and posts only, the full code would be:</p>
<pre><code>function que_styles(){
  if (!is_admin()) { //visitors only
    if (is_singluar() {
      wp_enqueue_style('mytheme-ie6');
    }
  }
}

add_action('wp_print_styles', 'que_styles')</code></pre>
<h4>Conclusion</h4>
<p>The methods described in this tutorial may appear to complicate matters for little pay off, especially if you&#8217;re developing a theme or plugin for your own site.</p>
<p>Replacing your &lt;script&gt; tags with the code above, it is true, will have almost no effect on the HTML or JavaScript output by WordPress. What&#8217;s worse, if you use the $ alias for jQuery in your JavaScript, you&#8217;ll need to edit both the theme&#8217;s php and JavaScript files.</p>
<p>These functions, <code>wp_register_script</code> and <code>wp_enqueue_script</code>, aren&#8217;t about now, however, they&#8217;re about “then”.</p>
<ul>
<li>Then&#8230; I activated this plugin and my JavaScript stopped working.</li>
<li>Then&#8230; I changed the theme and my favourite plugin stopped working</li>
<li>Then&#8230; I looked at the source code, and two copies of jQuery were being sent to every visitor</li>
</ul>
<p>The WordPress developers have seen the problems JavaScript conflicts can cause, and developed these functions to make your theme or plugin more robust. It&#8217;s the added robustness, for such little effort, that make these functions worth using.</p>
]]></content:encoded>
			<wfw:commentRss>http://bigredtin.com/2010/javascript-the-wordpress-way-part-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JavaScript the WordPress Way / Part 1</title>
		<link>http://bigredtin.com/2010/javascript-the-wordpress-way-part-1/</link>
		<comments>http://bigredtin.com/2010/javascript-the-wordpress-way-part-1/#comments</comments>
		<pubDate>Thu, 03 Jun 2010 05:44:42 +0000</pubDate>
		<dc:creator>Peter Wilson</dc:creator>
				<category><![CDATA[Behind the Websites]]></category>
		<category><![CDATA[coding]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[plugin]]></category>
		<category><![CDATA[theme]]></category>
		<category><![CDATA[WordPress]]></category>
		<category><![CDATA[wp_enqueue_script]]></category>
		<category><![CDATA[wp_register_script]]></category>

		<guid isPermaLink="false">http://bigredtin.pressgiant.net/?p=488</guid>
		<description><![CDATA[Problems arise when your theme or plugin both use the same JavaScript library or if Prototype and jQuery are both used on the same site. 

Two of the most important WordPress functions are often ignored by WordPress theme and plugin developers. Introducing: <code>wp_register_script</code> and <code>wp_enqueue_script</code>.]]></description>
			<content:encoded><![CDATA[<p>Two of the most important WordPress functions are often ignored by WordPress theme and plugin developers. This is the fault of the functions themselves, they need to improve their PR and hire better publicists.</p>
<p>It&#8217;s also possible your theme or plugin will work perfectly well without these functions on its own. Problems <em>will</em> arise when your theme or plugin both use the same JavaScript library or if Prototype and jQuery are both used on the same site.</p>
<p>These functions are used to add JavaScript to the html, either in the head or the footer.</p>
<p>Introducing <code>wp_register_script</code> and <code>wp_enqueue_script</code><span id="more-488"></span></p>
<p>For the rest of this article I&#8217;ll refer to development of <em>your theme</em>. The tutorial applies equally to development of <em>your plugin</em>, but there&#8217;s only so many times the phrase “your theme or plugin” can appear in a page.</p>
<p>In this first part, we&#8217;ll look at:</p>
<ul>
<li>Defining <a title="the problem" href="#jswpproblem">the problem</a>;</li>
<li>The <a title="libraries included" href="#jswplibraries">libraries included</a> with WordPress;</li>
<li>Defining <a title="the functions" href="#jswpfunctions">the functions</a> we&#8217;ll be using and;</li>
<li>The functions for <a title="registering" href="#jswpregister">registering</a> and <a title="enqueueing" href="#jsenqueue">enqueueing</a> your scripts.</li>
</ul>
<h4 id="jswpproblem">The problem defined</h4>
<p>Imagine you&#8217;ve used a theme on your WordPress site for months or years without a problem. It uses jQuery to add AJAX functionality to your site and it&#8217;s called <em>George&#8217;s Super Theme</em>.</p>
<p>You decide to add a plugin to your WordPress site and add more AJAXy goodness to your site. This plugin also uses jQuery for the JavaScript and it&#8217;s called <em>Richard&#8217;s Fabulous Plugin</em>.</p>
<p>You activate the plugin and instead of the super-fabulous result you were looking for you end up with a super-broken site. None of the JavaScript is working and your visitors are stuck on the home page, with nowhere to go.</p>
<p>Looking at the HTML of your WordPress site, you see the following lines:</p>
<pre><code>&lt;script type='text/javascript'
  src='/wp-content/themes/george/jquery-1.4.2.js'&gt;&lt;/script&gt;
&lt;script type='text/javascript'
  src='/wp-content/plugins/richard/jquery-1.3.2.js'&gt;&lt;/script&gt;</code></pre>
<p>Both the theme and the plugin are attempting to load the jQuery library. each uses a different version, which further complicates matters.</p>
<p>In this particular case, the theme is expecting jQuery version 1.4.2 and the plugin is replacing it with version 1.3.2. Anytime the theme attempts to use a function added to jQuery in version 1.4 or later, an error occurs preventing the JavaScript from running.</p>
<p>Even if the site was running as expected, it&#8217;s a waste of your users&#8217; bandwidth.</p>
<p>Fortunately the WordPress developers envisioned this problem and sort to solve it by including the most common JavaScript libraries with WordPress and developing the functions that are the subject of this tutorial.</p>
<h4 id="jswplibraries">Libraries included with WordPress</h4>
<p>WordPress comes with a number of JavaScript libraries pre-registered, so you need not include these libraries in your theme. All you need to do is include them as dependencies of your custom JavaScript and WordPress will do the work.</p>
<p>Some of the libraries included with WordPress are:</p>
<ul>
<li>jQuery – with the handle &#8216;jquery&#8217;, runs in <a title="no conflict mode" href="http://api.jquery.com/jQuery.noConflict/">no conflict mode</a>
<ul>
<li>WP 2.9.2 includes version 1.3.2 of jQuery</li>
<li>WP 3.0 will include version 1.4.2 of jQuery</li>
</ul>
</li>
<li>Scriptaculous – with the handle &#8216;scriptaculous&#8217;</li>
<li>SWFObject – with the handle &#8216;swfobject&#8217;</li>
<li>Prototype – with the handle &#8216;prototype&#8217;</li>
<li>A full list of pre-registered script can be found in the <a title="codex" href="http://codex.wordpress.org/Function_Reference/wp_enqueue_script#Default_scripts_included_with_WordPress">codex</a>.</li>
</ul>
<h4 id="jswpfunctions">The functions defined</h4>
<p>The <a title="WordPress codex defines wp_enqueue_script" href="http://codex.wordpress.org/Function_Reference/wp_enqueue_script">WordPress codex defines <code>wp_enqueue_script</code></a> as “a safe way of adding JavaScripts (sic) to a WordPress generated page”.</p>
<p><code>wp_register_script</code> is similar and can be thought of as a safe way of introducing JavaScript to WordPress, without adding it to the generated page.</p>
<p>The difference between these functions are fully explained in the sections <a title="Registering your scripts" href="#jswpregister"><em>Registering your scripts</em></a> and <em><a title="Enqueueing your scripts" href="#jsenqueue">Enqueueing your scripts</a></em> below.</p>
<p>Both functions take the same five parameters:</p>
<dl>
<dt>$handle</dt>
<dd>(required for both functions) Name of the script</dd>
<dt>$source</dt>
<dd>(required for <code>wp_register_script</code>) – URL of the script. Also required by <code>wp_enqueue_script</code> if the script is unregistered.</dd>
<dt>$dependancies</dt>
<dd>(optional) – an array of handles the script depends on</dd>
<dt>$version</dt>
<dd>(optional) – version number</dd>
<dt>$in_footer</dt>
<dd>(true/false, optional) – if true, place script above the HTML &lt;/body&gt; tag, otherwise place the script in the HTML &lt;head&gt;</dd>
</dl>
<p>These functions only work as expected if both <code>wp_head()</code> and <code>wp_footer()</code> are included in header.php and footer.php respectively.</p>
<h4 id="jswpregister">Registering your scripts – <code>wp_register_script</code></h4>
<p><code>wp_register_script</code> gives WordPress knowledge of your script without adding it to your HTML. <strong>Used by itself, it has no effect on your HTML whatsoever</strong>.</p>
<p>You can use it if you wish to register your various JavaScript files in one block of php within your theme&#8217;s functions.php file, allowing you to update version numbers, dependancies and handles in one place.</p>
<p>If the use of the JavaScript depends on particular conditions being met, such as the user being on a particular post, you can then enqueue your scripts elsewhere without losing track of where you should update version numbers.</p>
<p>If your theme&#8217;s JavaScript can be loaded in the footer and relies on the jQuery library, you would register your script with the following code:</p>
<pre><code>wp_register_script (
  'mytheme-custom', /* handle WP will know JS by */
  get_bloginfo('template_url') . '/custom.js', /* source */
  array('jquery'), /* requires jQuery */
  1.0, /* version 1.0 */
  true /* can load in footer */
);</code></pre>
<p>At this stage, this has no effect on your HTML, you need to use <code>wp_enqueue_script</code> to do that.</p>
<h4 id="jsenqueue">Enqueueing your scripts – <code>wp_enqueue_script</code></h4>
<p><code>wp_enqueue_script</code> outputs your JavaScript to the HTML of the page, either as a result of the w<code>p_head()</code> or the <code>wp_footer()</code> call in your PHP. If you have pre-registered your script (as above), the full code is:</p>
<pre><code>if (!is_admin()) {
  wp_enqueue_script('mytheme-custom');
}</code></pre>
<p>Combined with the code above, this line of code will load both jQuery and your theme&#8217;s JavaScript. The only reference to jQuery is needed in the dependancies. There is no need to register or enqueue it yourself.</p>
<p>The check that your visitor is outside of the admin area, <code>!is_admin()</code> – is important, as these functions can be used to add JavaScript to both the visitor and admin areas.</p>
<p>More often than not, you&#8217;ll want to leave the admin area alone.</p>
<h5>A shortcut</h5>
<p>It&#8217;s possible to enqueue your script without registering it first. This comes in handy if your theme uses a single JavaScript that is loaded on every page, outside the admin area, of your blog.</p>
<p>The code to do this is:</p>
<pre><code>if (!is_admin()) {
  wp_enqueue_script (
    'mytheme-custom', /* handle WP will know JS by */
    get_bloginfo('template_url') . '/custom.js', /* source */
    array('jquery'), /* requires jQuery */
    1.0, /* version 1.0 */
    true /* can load in footer */
  );
}</code></pre>
<p>Again, our custom code requires the jQuery Library.</p>
<h4>Aside: noConflict for jQuery and Prototype</h4>
<p>As mentioned earlier, jQuery runs in <a title="noConflict mode" href="http://api.jquery.com/jQuery.noConflict/">noConflict mode</a>. The reason being that in jQuery&#8217;s standard mode it includes the <code>$</code> variable as an alias. WordPress also includes Prototype, which includes the JavaScript variable <code>$</code>.</p>
<p>Imagine if your theme uses jQuery and you add a WordPress plugin that makes use of Prototype, whichever is loaded second would override the <code>$</code> variable of the former. Either your theme&#8217;s or the WordPress plugin&#8217;s JavaScript would crash as a result.</p>
<p>If your theme uses jQuery and you&#8217;d still like to make use of the <code>$</code> alias, it&#8217;s possible to do so without breaking the plugin&#8217;s JavaScript. In your JavaScript file, just wrap your code between these two lines:</p>
<pre><code>(function($) {
  /* your code */
})(jQuery);</code></pre>
<p>– <a title="source" href="http://codex.wordpress.org/Function_Reference/wp_enqueue_script#jQuery_noConflict_wrappers">source</a></p>
<p>Under no circumstances should you reintroduce the <code>$</code> alias for jQuery, it could lead to problems down the track.</p>
<p>A shorter aside: throughout this post I&#8217;m using the example of JavaScript requiring jQuery. The reasons are two-fold: a) it&#8217;s the library we use at <a title="Soupgiant" href="http://soupgiant.com">Soupgiant</a> and <a href="http://bigredtin.com">Big Red Tin</a> and, b) as Twitter&#8217;s Dustin Diaz said recently of jQuery: &#8216;<a title="they won" href="http://boagworld.com/technology/dustin-diaz">they won</a>&#8216;.</p>
<h4>Now Available: <a href="http://bigredtin.com/behind-the-websites/javascript-the-wordpress-way-part-2/" title="Part Two">Part Two</a></h4>
<p>In part 2 of this tutorial we&#8217;ll <a href="http://bigredtin.com/behind-the-websites/javascript-the-wordpress-way-part-2/#jswp2complicated">further illustrate dependancies</a>, <a href="http://bigredtin.com/behind-the-websites/javascript-the-wordpress-way-part-2/#jswp2googleapi" title="lower your bandwidth costs">lower your bandwidth costs</a> and show you how to use <a href="http://bigredtin.com/behind-the-websites/javascript-the-wordpress-way-part-2/#jswpcss" title="similar functions to load your stylesheets">similar functions to load your stylesheets</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://bigredtin.com/2010/javascript-the-wordpress-way-part-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

