<?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>Scriptble &#187; JC Fant IV</title>
	<atom:link href="http://scriptble.com/author/jcfant/feed/" rel="self" type="application/rss+xml" />
	<link>http://scriptble.com</link>
	<description>{ js : performance }</description>
	<lastBuildDate>Wed, 01 Feb 2012 20:02:54 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Removing Debug Statements from Javascript via compiler</title>
		<link>http://scriptble.com/2012/02/removing-debug-statements-from-javascript-via-compiler/</link>
		<comments>http://scriptble.com/2012/02/removing-debug-statements-from-javascript-via-compiler/#comments</comments>
		<pubDate>Wed, 01 Feb 2012 20:02:54 +0000</pubDate>
		<dc:creator>JC Fant IV</dc:creator>
				<category><![CDATA[Closure]]></category>
		<category><![CDATA[Compilers]]></category>
		<category><![CDATA[Debugging]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[closure compiler]]></category>
		<category><![CDATA[debugging]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://scriptble.com/?p=237</guid>
		<description><![CDATA[We all know the pain of getting a bug filed against some of your code and having to dig through it later to find the root cause. Especially, since many times we end up having to add back in all of our debug statements in order to track down the issue. There has to be [...]]]></description>
			<content:encoded><![CDATA[<p>We all know the pain of getting a bug filed against some of your code and having to dig through it later to find the root cause. Especially, since many times we end up having to add back in all of our debug statements in order to track down the issue. There has to be a better way. What if we could write all of our JavaScript with the debug code left in?</p>

<h2>The Better way</h2>

<p>By now, we are all using some compiler to compile your code. Right? If you haven't started, grab the <a href="http://closure-compiler.googlecode.com/files/compiler-latest.zip">Closure Compiler</a> to follow through on this example.</p>
<ol>
	<li>Download the latest Closure Compiler <a href="http://closure-compiler.googlecode.com/files/compiler-latest.zip">http://closure-compiler.googlecode.com/files/compiler-latest.zip</a></li>
	<li>Unzip</li>
	<li>Copy the compiler.jar file into your directory with the JS Files.</li>
	<li>follow along below and enjoy!</li>
</ol>

<p> If you are using Closure Compiler or Uglify already, you are in luck! Both of these compilers allow you to <a href="http://code.google.com/closure/compiler/docs/js-for-compiler.html">annotate your JavaScript</a>. Annotating your files allows you to describe them to the compiler. Things like @license will make sure that the comment goes to the top of the file after compression. Look through the <a href="http://code.google.com/closure/compiler/docs/js-for-compiler.html">http://code.google.com/closure/compiler/docs/js-for-compiler.html</a> list to see what each one does. We are going to focus on @define.</p>
<span id="more-237"></span>
<p>Take the following Code</p>
<pre class="language-javascript">
/**
 * @preserve Copyright 2009 SomeThirdParty.
 * Here is the full license text and copyright
 * notice for this file. Note that the notice can span several
 * lines and is only terminated by the closing star and slash:
 * BORROWED FROM THE ANNOTATED DOCS
 */

/** @define {boolean} */
var DEBUG = true;
var x = 1,
        y = 2;

var myNewObj = function(name, item) {
        var shortName = "Mr " + name,
                longName = "Dr. " + name + " M.D.S";

        this.getShortName = function() {
                if (DEBUG){
                        console.log("I am returning short name: " , shortName)
                }
                return shortName;
        }

        this.getLongName = function() {
                if (DEBUG){
                        console.log("I am returning long name: " , longName)
                }
                return longName;
        }

        return this;
}
// a bunch of your other code her

if (DEBUG) {
        var drWho = new myNewObj("Who", "blank");
        console.log(drWho.getLongName());
}

</pre>

<p>If we run the above code, we get the following output:</p>
<pre class-"language-javascript">
I am returning long name:  Dr. Who M.D.S
Dr. Who M.D.S
</pre>

<p> The above code would allow us to quickly turn on and off the debug statements and see what the JS code was doing. If we use this pattern, we can actually not worry about the value of DEBUG when we are finished with the file. We can actually change the value when we compile the input.</p>

<h2>The compiler</h2>

<p>If you take the above code and compress it using the following command: </p>

<pre class="language-java">
	java -jar compiler.jar --js input.js --define=DEBUG=false --js_output_file output.js --compilation_level SIMPLE_OPTIMIZATIONS --formatting PRETTY_PRINT
</pre>

<p>It will turn the output into:</p>

<pre class="language-javascript">
/*
 Copyright 2009 SomeThirdParty.
 Here is the full license text and copyright
 notice for this file. Note that the notice can span several
 lines and is only terminated by the closing star and slash:
 BORROWED FROM THE ANNOTATED DOCS
*/
var DEBUG = !1, x = 1, y = 2, myNewObj = function(a) {
  var b = "Mr " + a, c = "Dr. " + a + " M.D.S";
  this.getShortName = function() {
    DEBUG && console.log("I am returning short name: ", b);
    return b
  };
  this.getLongName = function() {
    DEBUG && console.log("I am returning long name: ", c);
    return c
  };
  return this
};
if(DEBUG) {
  var drWho = new myNewObj("Who", "blank");
  console.log(drWho.getLongName())
}
;
</pre>

<p>The compiled code now outputs the following:</p> 
<pre class-"language-javascript">
undefined
</pre>

<p>The return output for the new code is blank</p>

<h2>Advanced Compiling</h2>

<p>We can actually take this one step further, but be warned this is not for the faint of heart. If you want the statements removed completely you will need to rework your code just a bit.</p>

<p>Lets start with a modified version of the starting code:</p>
<pre class="language-javascript">
	/**
	* @preserve Copyright 2009 SomeThirdParty.
	* Here is the full license text and copyright
	* notice for this file. Note that the notice can span several
	* lines and is only terminated by the closing star and slash:
	* BORROWED FROM THE ANNOTATED DOCS
	*/                

	/** @define {boolean} */
	var DEBUG = true;
	var x = 1,              
	y = 2;          

	(function() {
	        /**
	          * A new Obj
	          * @constructor 
	          */            
	        myNewObj = function (name, item) {
	                this.shortName = "Mr " + name,
	                this.longName = "Dr. " + name + " M.D.S";

	                return this;
	        }

	        myNewObj.prototype.getLongName = function() {
	                /** 
	                  * @this {myNewObj}
	                  * @return {string}
	                  */
	                if (DEBUG){
	                        console.log("I am returning long name: " , this.longName)
	                }
	                return this.longName;
	        }

	        myNewObj.prototype.getShortName = function() { 
	                if (DEBUG){
	                        console.log("I am returning short name: " , this.shortName)
	                }
	                return this.shortName;
	        }

	        myNewObj.prototype['getLongName'] = myNewObj.prototype.getLongName;
	        myNewObj.prototype['getShortName'] = myNewObj.prototype.getShortName;

	        if (DEBUG) {
	                var drWho = new myNewObj("Who", "blank");
	                console.log(drWho.getLongName());
	        }
	})();
</pre>

<p>Here we moved the code into a closure function.</p>

<pre class="language-javascript">
	(function() {
	})();
</pre>

<p>Next we split the myNewObj into a constructor and prototypical inheritance. We also added a new annotation: @constructor. This tells the compiler that it is able to be invoked from other areas of the code.</p>

<pre class="language-javascript">
	/**
	  * A new Obj
	  * @constructor 
	  */            
	myNewObj = function (name, item) {
	        this.shortName = "Mr " + name,
	        this.longName = "Dr. " + name + " M.D.S";

	        return this;
	}

	myNewObj.prototype.getLongName = function() {
	        /** 
	          * @this {myNewObj}
	          * @return {string}
	          */
	        if (DEBUG){
	                console.log("I am returning long name: " , this.longName)
	        }
	        return this.longName;
	}

	myNewObj.prototype.getShortName = function() { 
	        /** 
	          * @this {myNewObj}
	          * @return {string}
	          */
	        if (DEBUG){
	                console.log("I am returning short name: " , this.shortName)
	        }
	        return this.shortName;
	}
</pre>

<p>Next, we need to make sure that the functions are available to everyone else. Since the advanced compiler will change all variable names, and delete portions of code that aren't reachable, we will make them reachable again. We do this by attaching each of the available functions onto the objects prototype again. For more information on this, check out <a href="http://code.google.com/closure/compiler/docs/api-tutorial3.html#export">Advanced Compilation and Externs</a> tutorial on Closure Compiler.</p>

<pre class="language-javascript">

	myNewObj.prototype['getLongName'] = myNewObj.prototype.getLongName;
	myNewObj.prototype['getShortName'] = myNewObj.prototype.getShortName;	

</pre>

<p>Now that we have the JavaScript setup properly, we can compile to see what the output becomes. We compile the code with the following options</p>


<pre class="language-java">
	java -jar compiler.jar --js input.js --define=DEBUG=false --js_output_file output.js --compilation_level ADVANCED_OPTIMIZATIONS --formatting PRETTY_PRINT --generate_exports
</pre>

<p>It will turn the output into:</p>

<pre class="language-javascript">
/*
 Copyright 2009 SomeThirdParty.
 Here is the full license text and copyright
 notice for this file. Note that the notice can span several
 lines and is only terminated by the closing star and slash:
 BORROWED FROM THE ANNOTATED DOCS
*/
myNewObj = function(a) {
  this.d = "Mr " + a;
  this.c = "Dr. " + a + " M.D.S";
  return this
};
myNewObj.prototype.a = function() {
  return this.c
};
myNewObj.prototype.b = function() {
  return this.d
};
myNewObj.prototype.getLongName = myNewObj.prototype.a;
myNewObj.prototype.getShortName = myNewObj.prototype.b;
</pre>

<h2>Summary</h2>

<p>Don't feel overwhelmed trying out the advanced optimizations. Sometimes it just takes some playing around with the code to get it into the best possible outcome. If you aren't that familiar with JavaScript, I would highly recommend sticking with the SIMPLE_OPTIMIZATIONS and just having a slightly bigger file to content with.</p>

]]></content:encoded>
			<wfw:commentRss>http://scriptble.com/2012/02/removing-debug-statements-from-javascript-via-compiler/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A Textmate Bundle for CSSLint</title>
		<link>http://scriptble.com/2011/06/a-textmate-bundle-for-csslint/</link>
		<comments>http://scriptble.com/2011/06/a-textmate-bundle-for-csslint/#comments</comments>
		<pubDate>Fri, 17 Jun 2011 22:07:55 +0000</pubDate>
		<dc:creator>JC Fant IV</dc:creator>
				<category><![CDATA[CSSLint]]></category>

		<guid isPermaLink="false">http://scriptble.com/?p=228</guid>
		<description><![CDATA[CSSLint A quick heads up, if you haven't heard about the new CSSLint project from Nicole ## and Nicholas Zakas, you have been missing out. The project aims to take CSS to the next level and help you understand why your css isn't performing very well. What, you didn't know your CSS isn't performing? Thats [...]]]></description>
			<content:encoded><![CDATA[<h1>CSSLint</h1>
<p>A quick heads up, if you haven't heard about the new <a href="http://csslint.net">CSSLint</a> project from Nicole ## and Nicholas Zakas, you have been missing out. The project aims to take CSS to the next level and help you understand why your css isn't performing very well. What, you didn't know your CSS isn't performing? Thats because most of us haven't had a good Code Review on most of our CSS.</p>

<h2>CSSLint for TextMate</h2>

<p>First and foremost, I would like to say, <b>I forked the original <a href="http://fgnass.posterous.com/jslint-in-textmate">jsHint TextMate Bundle</a></b>. If you don't already have this, you need it. It will change the way you put together your JavaScript, just as I suspect CSSLint will do for your CSS.</p>

<p>I talked with Nicholas at the Velocity conference and decided I would put together a quick <a href="https://github.com/jcfant/csslint.tmbundle">CSSLint TextMate Bundle</a> that could make use of the Node Module for CSSLint. After a couple of hours playing with the way TextMate Does its bundles, I was able to get a working product. A Couple of quick emails back and forth and we have a Beta version of the CSSLint TextMate Bundle.</p>
<span id="more-228"></span>

<h3>Installation</h3>
<p>Installation is simple. Just download this file <a href="http://github.com/jcfant/csslint.tmbundle/zipball/master">CSSLint TextMate Bundle</a>. Unzip the contents, and then rename the file to csslint.tmbundle.</p>
<p>Once you have renamed, just double click on the icon, and it should automatically add it to TextMate.</p>

<h3>Prerequisites</h3>
<p>You need <a href="http://nodejs.org/">Node.js</a> and TextMate, that's all.</p>
<p>If you don't have <a href="http://nodejs.org/">Node.js</a> installed on your system you can also use <a href="https://github.com/bpierre/jshint.tmbundle">Pierre Bertet's</a> fork which uses <a href="http://trac.webkit.org/wiki/JSC">WebKit's JavaScriptCore</a> instead.</p>

<p>This bundle uses #!/usr/local/bin/node to launch the node process. If you get a node - not found error,the PATH variable is probably not setup in TextMate.</p>

<h3>Features</h3>
<p>
	A couple of quick highlights.
	<ul>
		<li>Runs automatically upon save (⌘S)</li>
		<li>Can be bypassed by pressing ⇧⌘S</li>
		<li>Output is only shown when errors are found</li>
		<li>Based on Node.js</li>
	</ul>
</p>

<h3>ScreenShot</h3>
<p>
<img src="https://github.com/jcfant/images/raw/master/CSSLintTMBundle.jpg" height="384" width="579" />
</p>

<h3>Contributions</h3>
<p>
	Feel free to contact me about any features you would like to see in the bundle. Or submit a pull request and I will take a look.
</p>

<p>Cheers!</p>
<p>JC Fant</p>]]></content:encoded>
			<wfw:commentRss>http://scriptble.com/2011/06/a-textmate-bundle-for-csslint/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Parallel Downloading HTML Assets</title>
		<link>http://scriptble.com/2011/05/parallel-downloading-html-assets/</link>
		<comments>http://scriptble.com/2011/05/parallel-downloading-html-assets/#comments</comments>
		<pubDate>Mon, 16 May 2011 21:10:50 +0000</pubDate>
		<dc:creator>JC Fant IV</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[inline script]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://scriptble.com/?p=210</guid>
		<description><![CDATA[Question: Image - inline Script - image, are the images parallel? Souders just posted the following tweet. Someone out in #webperf land should test how inline scripts block downloads - eg, image - inline script - image - are the images parallel? So here is my response to the question... Answer: No The Test Page [...]]]></description>
			<content:encoded><![CDATA[<h1>Question: Image - inline Script - image, are the images parallel?</h1>

<p>Souders just posted the following tweet.</p>
<blockquote>Someone out in #webperf land should test how inline scripts block downloads - eg, image - inline script - image - are the images parallel?</blockquote>
<p> So here is my response to the question... </p>

<span id="more-210"></span>
<h1>Answer: No</h1>

<h2>The Test Page</h2>

<p>
	The page itself is pretty simple, two images served from <a href="http://placehold.it/">placehold.it</a> and in between them, jQuery 1.5.2 in an inline script block.
	Take a look at the <a href="/tests/scriptTest.html">sample test here</a>. 
</p>

<h2>The Tests</h2>

<p>
	Using <a href="http://webpagetest.org">webpagetest.org</a>, I ran the scriptTest.html file through IE6|7|8|9 and Chrome 11. In each of the browsers the waterfall graph 
	comes out the same. The inline script blocks any more downloads until the script has finished parsing and been run.
</p>

<h2>Waterfall Graphs</h2>

<p>Here are the waterfall graphs for each of the browsers on webpagetest.org</p>

<h3>IE6</h3>
<p><img src="http://www.webpagetest.org/results/11/05/16/S0/M7QN/1_waterfall.png" width="585" height="128"/></p>
<p><a href="http://www.webpagetest.org/result/110516_S0_M7QN/1/details/">Test Results</a></p>

<h3>IE7</h3>
<p><img src="http://www.webpagetest.org/results/11/05/16/3K/M7QP/1_waterfall.png" width="585" height="128" /></p>
<p><a href="http://www.webpagetest.org/result/110516_3K_M7QP/1/details/">Test Results</a></p>

<h3>IE8</h3>
<p><img src="http://www.webpagetest.org/results/11/05/16/GE/M7QQ/1_waterfall.png" width="585" height="128" /></p>
<p><a href="http://www.webpagetest.org/result/110516_GE_M7QQ/1/details/">Test Results</a></p>

<h3>IE9</h3>
<p><img src="http://www.webpagetest.org/results/11/05/16/CA/M7QS/1_waterfall.png" width="585" height="128" /></p>
<p><a href="http://www.webpagetest.org/result/110516_CA_M7QS/1/details/">Test Results</a></p>

<h3>Chrome 11</h3>
<p><img src="http://www.webpagetest.org/results/11/05/16/DC/M7QT/1_waterfall.png" width="585" height="128" /></p>
<p><a href="http://www.webpagetest.org/result/110516_DC_M7QT/1/details/">Test Results</a></p>

<h2>But Wait!</h2>

<p>This isn't just about images and inline style blocks. What happens when we use a style sheet? Will it give the same behavior?</p>

<h2>Next Test</h2>

<p>Here is a <a href="http://scriptble.com/tests/scriptTestStyles.html">new test</a>, it has an external style sheet (style.css), the inline JavaScript block, another external style sheet (screen.css) and an image from placehold.it.<p>

<h2>Results</h2>

<p>In each case the inline JavaScript is blocking the page from getting any more resources. As soon as the JavaScript has been processed it can then move on to getting the background image, screen.css and the placeholder.it image.<p>

<h3>IE6</h3>
<p><img src="http://www.webpagetest.org/results/11/05/16/ST/M7T9/1_waterfall.png" width="585" height="128" /></p>
<p><a href="http://www.webpagetest.org/result/110516_ST_M7T9/1/details/">Test Results</a></p>

<h3>IE7</h3>
<p><img src="http://www.webpagetest.org/results/11/05/16/HX/M7TC/1_waterfall.png" width="585" height="128" /></p>
<p><a href="http://www.webpagetest.org/result/110516_HX_M7TC/1/details/">Test Results</a></p>

<h3>IE8</h3>
<p><img src="http://www.webpagetest.org/results/11/05/16/D0/M7TE/1_waterfall.png" width="585" height="128" /></p>
<p><a href="http://www.webpagetest.org/result/110516_D0_M7TE/1/details/">Test Results</a></p>

<h3>IE9</h3>
<p><img src="http://www.webpagetest.org/results/11/05/16/04/M7TH/1_waterfall.png" width="585" height="128" /></p>
<p><a href="http://www.webpagetest.org/result/110516_04_M7TH/1/details/">Test Results</a></p>

<h3>Chrome 11</h3>
<p><img src="http://www.webpagetest.org/results/11/05/16/6N/M7TN/1_waterfall.png" width="585" height="128" /></p>
<p><a href="http://www.webpagetest.org/result/110516_6N_M7TN/1/details/">Test Results</a></p>

<h2>Conclusion</h2>
<p>Be careful with your inline blocks. They CAN AND WILL hold up the rest of your page when they are encountered.</p>
]]></content:encoded>
			<wfw:commentRss>http://scriptble.com/2011/05/parallel-downloading-html-assets/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Getting A Class From a DOM Element</title>
		<link>http://scriptble.com/2011/05/getting-a-class-from-a-dom-element/</link>
		<comments>http://scriptble.com/2011/05/getting-a-class-from-a-dom-element/#comments</comments>
		<pubDate>Fri, 13 May 2011 19:34:32 +0000</pubDate>
		<dc:creator>JC Fant IV</dc:creator>
				<category><![CDATA[Do This, Not That]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[DOM Manipulation]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://scriptble.com/?p=200</guid>
		<description><![CDATA[Lately, if I am searching for a way to do something in Javascript the only results I am getting ways of doing the procedure using jQuery. While, its true jQuery is pretty much the de facto standard for writing JavaScript anymore, understanding the underlying technology is a must. As well as alot of times, I [...]]]></description>
			<content:encoded><![CDATA[<p>Lately, if I am searching for a way to do something in Javascript the only results I am getting ways of doing the procedure using jQuery. While, its true jQuery is pretty much the de facto standard for writing JavaScript anymore, understanding the underlying technology is a must. As well as alot of times, I don't need to load jQuery on the page just to get a DOM Element or its class.</p>

<p>So I recently went looking on how to <a href="http://tinyurl.com/3w5m6t5">get class from element</a> in JavaScript. Turns out most of the results were for getting elements by class name, rather than actually getting the class of the element I already had.</p>

<p>Here is how you get a class name from an Element using JavaScript.</p>
<span id="more-200"></span>
<pre class="language-javascript">
	document.getElementById("tag_cloud-2").className
</pre>
<br/>
<pre>
	Output:
		"sidebaritem widget_tag_cloud"
</pre>
<br/>
<p>Now, that wasn't so hard.  Lets take a look at a performance test: <a href="http://jsperf.com/jquery-versus-classname">jQuery versus getting a className</a>.</p>

<p>Here is the setup for the test</p>
<pre>
&lt;script src="//ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"&gt;&lt;/script&gt;

&lt;div class="wrapper"&gt;
	&lt;div class="innerWrapper"&gt;
		&lt;div id="getMe" class="button"&gt;
			&lt;a href="javascript:void(0)" id="button" class="buttonRef"&gt;
				&lt;span class="buttonText"&gt;Text&lt;/span&gt;
			&lt;/a&gt;
		&lt;/div&gt;
	&lt;/div&gt;
&lt;/div&gt;

&lt;script&gt;
	var jElem = $("#getMe");
	var dElem = document.getElementById("getMe");
&lt;/script&gt;
</pre>
<br/>
<p>Here are the tests:</p>
<pre>
1. jQuery - get Element + get Class   $("#getMe").attr('class');
2. GET DOM ELEM + get Class           document.getElementById("getMe").className;
3. jQuery get Class                   jElem.attr('class');
4. DOM get class                      dElem.className;
</pre>

<h2>Chrome 11 Results</h2>
<p>
In Chrome using a cached element, getting the classname is 48x faster than using jQuery.<br/>
In Chrome getting the element and then getting the classname is 25x faster than using jQuery.<br/>
</p>

<h2>FF 4.0 Results</h2>
<p>
In FF using a cached element, getting the classname is 65x faster than using jQuery.<br/>
In FF getting the element and then getting the classname is 83x faster than using jQuery.<br/>
</p>

<h2>Safari 5.0 Results</h2>
<p>
In Safari using a cached element, getting the classname is 30x faster than using jQuery.<br/>
In Safari getting the element and then getting the classname is 35x faster than using jQuery.<br/>
</p>

<h3>Summary</h3>
<p>
	Whenever possible, using the browsers built in methods will always be faster, and just because you have a library available doesn't mean you should be using it for every DOM query. The speed advantage alone should dictate which methods of the library you are using and when.
</p>
]]></content:encoded>
			<wfw:commentRss>http://scriptble.com/2011/05/getting-a-class-from-a-dom-element/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Lazy Loading Functions</title>
		<link>http://scriptble.com/2011/05/lazy-loading-functions/</link>
		<comments>http://scriptble.com/2011/05/lazy-loading-functions/#comments</comments>
		<pubDate>Fri, 13 May 2011 04:05:52 +0000</pubDate>
		<dc:creator>JC Fant IV</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Functions]]></category>
		<category><![CDATA[Objects]]></category>

		<guid isPermaLink="false">http://scriptble.com/?p=193</guid>
		<description><![CDATA[The best part about this Javascript pattern is the ability to calculate once and then use the new function definition from that point forward. During the course of building web apps, we usually end up with functions to do certain tasks. However, since those tasks sometimes need to be done differently in each of the [...]]]></description>
			<content:encoded><![CDATA[<p>The best part about this Javascript pattern is the ability to calculate once and then use the new function definition from that point forward.</p>

<p>During the course of building web apps, we usually end up with functions to do certain tasks. However, since those tasks sometimes need to be done differently in each of the browsers, we end up with large if else statements to get the job done.</p>

<p>This is where Self Defining Functions come in handy.</p>
<span id="more-193"></span>
<p>Here is a simple Person Object that has a getPayInformation object. Lets assume for the sake of the argument that this function is called 100's of times. In this case, each time the getPayInformation function is called, it first has to figure out the role, then do the calculations for the pay.</p>

<pre class="language-javascript">
function Person(name, role) {
    if (!(this instanceof Person)){
        return new Person(name, role);
    }

    this.name = name || "John";
	this.role = role || "Guest";
};

Person.prototype.getPayInformation = function() {
	if (this.role === "Admin"){
		// fetch some data for the admin role. 
		// do some awesome calculations to munge the data 
		// ...
		return {
			"role"  : "Admin",
			"rate"  : 10.00,
			"hours" : 40
		};
	}else if (this.role === "CopyCat"){
		// fetch some data for the admin role. 
		// Calculating the Info for a copy cat is harder. Has some different calculations based on 
		// how many words they wrote
		// ...
		return {
			"role"  : "CopyCat",
			"rate"  : 37.00,
			"hours" : 23
		};
	}else if (this.role === "Crane Operator"){
		// fetch some data for the admin role. 
		// Calculating the info for a crane operator is based on hourly, anything over 40 is time and a half.
		// ...
		return {
			"role"  : "Crane Operator",
			"rate"  : 90.00,
			"hours" : 42
		};
	}else{ 
		// fetch some data for the admin role. 
		// we don't need to do anything for the guest, its always 0.
		// ...
		return {
			"role"  : "Guest",
			"rate"  : 0.00,
			"hours" : 0
		};
	}
}
</pre>
<br/>
<p>What would happen if we knew that after the first time through this person was an admin. We would no longer need to do that check over and over again.</p>

<pre class="language-javascript">
function Person(name, role) {
    if (!(this instanceof Person)){
        return new Person(name, role);
    }

    this.name = name || "John";
	this.role = role || "Guest";
};

Person.prototype.getPayInformation = function() {
	if (this.role === "Admin"){
		this.getPayInformation = function() {
			console.log("Lazy Function Definition");
			// fetch some data for the admin role. 
			// do some awesome calculations to munge the data 
			// ...
			return {
				"role"  : "Admin",
				"rate"  : 10.00,
				"hours" : 40
			};
		}
		return this.getPayInformation();
	}else if (this.role === "CopyCat"){
		this.getPayInformation = function() {
			console.log("Lazy Function Definition");
			// fetch some data for the admin role. 
			// Calculating the Info for a copy cat is harder. Has some different calculations based on 
			// how many words they wrote
			// ...
			return {
				"role"  : "CopyCat",
				"rate"  : 37.00,
				"hours" : 23
			};
		}
		return this.getPayInformation();
	}else if (this.role === "Crane Operator"){
		this.getPayInformation = function() {
			console.log("Lazy Function Definition");
			// fetch some data for the admin role. 
			// Calculating the info for a crane operator is based on hourly, anything over 40 is time and a half.
			// ...
			return {
				"role"  : "Crane Operator",
				"rate"  : 90.00,
				"hours" : 42
				};	
		}
		return this.getPayInformation();
	}else{ 
		this.getPayInformation = function() {
			console.log("Lazy Function Definition");
			// fetch some data for the admin role. 
			// we don't need to do anything for the guest, its always 0.
			// ...
			return {
				"role"  : "Guest",
				"rate"  : 0.00,
				"hours" : 0
			};	
		}
		return this.getPayInformation();
	}
}
</pre>
<br/>
<p>Now, we only have to do the check once and then each subsequent calls can skip the check and just get to work.</p>

<p>So what does the output look like?</p>

<pre class="language-javascript">
	var tammy = new Person("Tammy", "Admin");
	console.log(tammy.getPayInformation());
		"Lazy Function Definition"
		> Object
			{
				"role"  : "Admin",
				"rate"  : 10.00,
				"hours" : 40
			}
			
	var john = new Person("John", "Guest");
	console.log(john.getPayInformation());
		"Lazy Function Definition"
		> Object
			{
				"role"  : "Guest",
				"rate"  : 0.00,
				"hours" : 0
			}
	
	var lola = new Person("Lola", "CopyCat");
	console.log(lola.getPayInformation());
		"Lazy Function Definition"
		> Object
			{
				"role"  : "CopyCat",
				"rate"  : 37.00,
				"hours" : 23
			}
			
	var chad = new Person("Chad", "Crane Operator");
	console.log(chad.getPayInformation());
		"Lazy Function Definition"
		> Object
			{
				"role"  : "Crane Operator",
				"rate"  : 90.00,
				"hours" : 42
			}
</pre>
<br/>
<p>Looks to be a pretty neat way to do Browser Feature detection instead of nested if statements. Moving to a Module pattern helps to support the Self Defining Function Pattern.</p>
]]></content:encoded>
			<wfw:commentRss>http://scriptble.com/2011/05/lazy-loading-functions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>jQuery ready, delegate, live!</title>
		<link>http://scriptble.com/2011/03/jquery-ready-delegate-live/</link>
		<comments>http://scriptble.com/2011/03/jquery-ready-delegate-live/#comments</comments>
		<pubDate>Wed, 09 Mar 2011 18:18:51 +0000</pubDate>
		<dc:creator>JC Fant IV</dc:creator>
				<category><![CDATA[jQuery]]></category>
		<category><![CDATA[.delegate()]]></category>
		<category><![CDATA[.live()]]></category>
		<category><![CDATA[.ready()]]></category>

		<guid isPermaLink="false">http://scriptble.com/?p=177</guid>
		<description><![CDATA[Recently I was browsing through the jQuery subr reddit and noticed this question pop up. Since I am sure this is a pretty common question on "Why won't my jQuery command work properly", I figured I would give a shot at answering it. Hey guys, I'm sure this has been answered before but I can't [...]]]></description>
			<content:encoded><![CDATA[<p>
	Recently I was browsing through the jQuery subr reddit and noticed this question pop up. Since I am sure this is a pretty common question on "Why won't my jQuery command work properly", I figured I would give a shot at answering it.
</p>

<blockquote>
Hey guys, I'm sure this has been answered before but I can't seem to find anything by searching Google or /r/jquery.

I am a beginner with this so forgive me, but I can't find an explanation to this anywhere and I'm curious. When I try to stop the default submit function of a form in the &lt;head&gt; tag of a .html file it won't work, but when I copy and paste the same code into the &lt;body&gt; it works fine. Regardless of where I place it, it is always below the link to the jquery library. This is really confusing and I was hoping you guys could explain this for me. Thanks!

via <a href="http://www.reddit.com/r/jquery/comments/fwtwh/jquery_script_in_body_or_head/">jQuery &lt;script&gt; in &lt;body&gt; or *lt;head&gt;</a>.
</blockquote>

<span id="more-177"></span>
<h2>Problem</h2>
<p>
	Here was a copy of the code that worked:
</p>

<code class="language-javascript">
&lt;html&gt;
	&lt;head&gt;
		&lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript" charset="utf-8"&gt;&lt;/script&gt;

	&lt;/head&gt;
	&lt;body&gt;

	&lt;script&gt;
    	$("form").submit(function(){
        	return false;
    		});
	&lt;/script&gt;
	&lt;form id="uriForm" action=""&gt;
		&lt;input type="textbox" name="uriInput" id="uriInput" /&gt;
		&lt;input type="submit" value="submit" id="submit" /&gt;
	&lt;/form&gt;
	&lt;/body&gt;
&lt;/html&gt;
</code>
<br/>
<p>
	However, if he moved the &lt;script&gt; tag into the head, the form submit stopped working.
</p>

<code class="language-javascript">
	&lt;head&gt;
		&lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript" charset="utf-8"&gt;&lt;/script&gt;

		&lt;script&gt;
	    	$("form").submit(function(){
	        	return false;
	    		});
		&lt;/script&gt;
	&lt;/head&gt;
</code>
<br/>
<h2>Why?</h2>
<p>
	Why on earth would the first one work, and the second one not? Well, it comes down to when the dom is ready. In the second example, jQuery is looking for a form tag that hasn't been parsed by the browser yet. So it returns an empty jQuery object, to which the submit event is attached.
</p>

<h2>The Fix</h2>
<p>
	We have a couple of ways of fixing this issue. 
</p>

<h3>.ready()</h3>
<p>The .ready() event attached to the BODY tag, will allow us to attach the submit event as soon as the DOM is ready</p>
<code class="language-javascript">
	$(document).ready(function() {
		$("form").submit(function() {
			return false;
		});
	})
</code>
<br/>

<h3>.delegate()</h3>
<p>
	The .delegate() method can be placed anywhere in your page. Since the delegate function will attach the event to any current "form" elements, or any future "form" elements that may appear in the DOM. The gotcha... If you only have one form element on the page, this will work fine. However, IF for some reason, you create another form element, this same event will be attached to that form as well. 
</p>

<code class="language-javascript">
	$(document).delegate("form", function() {
		$("form").submit(function() {
			return false;
		});
	})
</code>
<br/>

<h3>.live()</h3>
<p>
	The .live() method is a variation/alternative of the .delegate() method. However, at least one element must exist before you can use it. Which means, you still need to wrap it in a .ready() or put it in the footer. 
</p>
<blockquote>
	This method is a variation on the basic .bind() method for attaching event handlers to elements. When .bind()  is called, the elements that the jQuery object refers to get the handler attached; elements that get introduced later do not, so they would require another .bind() call. 
</blockquote>


<code class="language-javascript">
	$(document).ready(function() {
		$("form").live("submit", function() {
			return false;
		});
	})
</code>
<br/>

<p>
	In all, either .ready() or .delegate() will work, just make sure you use them properly. You don't want to add another form or other element and have it get an event you hadn't planned on.
</p>]]></content:encoded>
			<wfw:commentRss>http://scriptble.com/2011/03/jquery-ready-delegate-live/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Patterns for enforcing &#8220;new&#8221;</title>
		<link>http://scriptble.com/2011/03/patterns-for-enforcing-new/</link>
		<comments>http://scriptble.com/2011/03/patterns-for-enforcing-new/#comments</comments>
		<pubDate>Sun, 06 Mar 2011 04:49:59 +0000</pubDate>
		<dc:creator>JC Fant IV</dc:creator>
				<category><![CDATA[Do This, Not That]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[patterns]]></category>

		<guid isPermaLink="false">http://scriptble.com/?p=184</guid>
		<description><![CDATA[Recently I was looking around for a book on JavaScript Patterns. I decided to give the JavaScript Patterns by Stoyan Stefanov a try. If you have been looking for a book on Javascript Patterns, I highly recommend this book. In the 3rd chapter, Literals and Constructors, I noticed this section on "Patterns for enforcing new" [...]]]></description>
			<content:encoded><![CDATA[<p>
	Recently I was looking around for a book on JavaScript Patterns. I decided to give the <a href="http://www.amazon.com/JavaScript-Patterns-Stoyan-Stefanov/dp/0596806752/ref=sr_1_1?ie=UTF8&qid=1299384435&sr=8-1">JavaScript Patterns</a> by Stoyan Stefanov a try. If you have been looking for a book on Javascript Patterns, I highly recommend this book. 
</p>

<p>
	In the 3rd chapter, Literals and Constructors, I noticed this section on "Patterns for enforcing new" with the following entry:
</p>

<blockquote>
	When your constructor has something like <i>this.member</i> and you invoke the constructor without <i>new</i>, you're actually creating a new property of the global object called <i>member</i> and accessible through <b>window.<i>member</i></b> or simply <i>member</i>. This behavior is highly undesirable, because you know you should always strive for keeping the global namespace clean.
</blockquote>
<span id="more-184"></span>
<p>
	Take a look at the following code:
</p>

<code class="language-javascript">
	function Person(name) {
		this.personName = name || "John";
	}

	var tammy = new Person("tammy");
	console.log(typeof tammy); // Object
	console.log(tammy instanceof Person); // true
	console.log(tammy.personName); // tammy
	console.log(window.personName); // undefined
	
	var jason = Person("jason");
	console.log(typeof jason); // undefined
	console.log(jason instanceof Person); // false
	console.log(window.personName); // jason
</code>
<br/>
<p>
	Eek! Thats not what I expected at all. So how can we force this to always create a new Object each time, regardless of whether or not the Object ("function") has been called with new? 
</p>

<h2>Solutions</h2>

<p>
	There are a couple of solutions. We can either, change the scope of the internal variable to something other than "this" OR we can always force a "new" on the object.
</p>

<h3>Use "that"</h3>

<p>
	If we change the function to create a new object called "that" and then assign personName to the new object, we can make sure that the global namespace isn't polluted.
</p>

<code class="language-javascript">
	function Person(name) {
		var that = {};
		that.personName = name || "John";
		
		return that;
	}

	var tammy = new Person("tammy");
	console.log(typeof tammy); // Object
	console.log(tammy instanceof Person); // false
	console.log(tammy.personName); // tammy
	console.log(window.personName); // undefined
	
	var jason = Person("jason");
	console.log(typeof jason); // Object
	console.log(jason instanceof Person); // false
	console.log(jason.personName); // jason
	console.log(window.personName); // undefined
</code>
<br/>
<p>
	Well, that is much better. However, if we check whether or not "jason" or "tammy" are actually people we see that both fail. So while this gets us to the point of not polluting the global namespace we aren't creating actual "people".
</p>

<h3>Force "new"</h3>

<p>
	We can actually check to see if "this" is an instance of Person, if not, returning a "new Person".
</p>

<code class="language-javascript">
	function Person(name) {
		if (!(this instanceof Person)){
			return new Person(name);
		}

		this.personName = name || "John";

	}
	
	var tammy = new Person("tammy");
	console.log(typeof tammy); // Object
	console.log(tammy instanceof Person); // true
	console.log(tammy.personName); // tammy
	console.log(window.personName); // undefined

	var jason = Person("jason");
	console.log(typeof jason); // Object
	console.log(jason instanceof Person); // true
	console.log(jason.personName); // jason
	console.log(window.personName); // undefined
</code>
<br/>
<p>
	Much better, now we actually have true instances of "Person". 
</p>

<p>
	The good news in all of this is that in ECMAScript5 strict mode, this no longer applies. As the "this" reference will no longer point to the global namespace.
</p>]]></content:encoded>
			<wfw:commentRss>http://scriptble.com/2011/03/patterns-for-enforcing-new/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Closure Versus Prototypal Object Creation</title>
		<link>http://scriptble.com/2011/02/closure-versus-prototypal-object-creation/</link>
		<comments>http://scriptble.com/2011/02/closure-versus-prototypal-object-creation/#comments</comments>
		<pubDate>Fri, 18 Feb 2011 05:14:16 +0000</pubDate>
		<dc:creator>JC Fant IV</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Performance]]></category>

		<guid isPermaLink="false">http://scriptble.com/?p=162</guid>
		<description><![CDATA[I was just looking through a new blog post from Brendan Eich over on AMinuteWithBrendan where he went into some detail on Closures versus Prototypal Patterns. After listening to his pod cast, (you can find the transcript here), I decided to put the two patterns to test. So I fired up a new test on [...]]]></description>
			<content:encoded><![CDATA[<p>
	I was just looking through a new blog post from Brendan Eich over on 
	<a href="http://www.aminutewithbrendan.com/">AMinuteWithBrendan</a> where he went into some detail on <a href="http://www.aminutewithbrendan.com/pages/20110216">Closures versus 
	Prototypal Patterns</a>.
</p>

<p>After listening to his pod cast, (you can find the transcript <a href="http://piratepad.net/amwb-20110216">here</a>), I decided to put
the two patterns to test. So I fired up a new test on <a href="http://jsperf.com/object-creation-patterns">JSPerf.com</a></p>
<span id="more-162"></span>
<br/><br/><br/><br/>

<h5>Setting up the Closure Pattern</h5>

<code class="language-javascript">
 function ClosurePattern() {
  this.someMethod = function someMethod() {
   console.log('foo');
  }
 }
 </code>
 <br/>
 
 <h5>Setting up the Prototypal Pattern</h5>
 
 <code class="language-javascript">
 function PrototypalPattern() {}
 PrototypalPattern.prototype = {
  someMethod: function() {
   console.log('foo');
  }
 }
 </code>
 
 <h5>Setting up the Prototypal Hoisting Pattern</h5>
 
 <code class="language-javascript">
 function sm() {
  console.log("foo")
 }
 
 function PrototypalWithHoisting() {}
 PrototypalWithHoisting.prototype = {
  someMethod: sm
 }
 </code>
<br/>

<h3>Results</h3>


<h5>Closure Pattern</h5>

<img src="/images/closurePatterns/closure.png" alt="Closure Pattern"/>
<br/>
<br/>
<p>The closure pattern is quick in Chrome, but not nearly as fast in all the other browsers.</p>

<h5>Prototypal Versus Hoisting</h5>

<img src="/images/closurePatterns/prototypalVhoisting.png" alt="Prototypal Versus Hoisting"/>
<br/>
<br/>

<p>Prototypal and hoisting run neck and neck in all browsers, with Prototypal winning out in Chrome.</p>

<h5>Closure Versus Prototypal</h5>

<img src="/images/closurePatterns/closureVersusPrototype.png" alt="Closure Versus Prototypal"/>
<br/>
<br/>

<p>Here we are can start to se the overall winner in object creation.</p>

<h5>Closure, Prototypal, Hoisting</h5>

<img src="/images/closurePatterns/closureAndProto.png" alt="Closure, Prototypal, Hoisting"/>
<br/>
<br/>
<p>I threw this one up here so you can see all 3 types next to each other. </p>

<h3>Conclusion</h3>

<p>
	After look at this set of test, I really think it all depends on your use case. While the Closure Pattern lends itself to 
	readability and the ability to have both public and private variables as well as public and private methods, object creation is 
	much slower. Also, as Brendan points out, you aren't getting the same functionality as creating an object via the Prototypal Pattern.
</p>

<blockquote>
	The closure pattern, the one where you have the method as a function expression inside the constructor, can actually be more 
	expensive. If you think about it, each time you call that constructor (let's say you call it a million times), you have to 
	evaluate the method function expression. You have to evaluate the assignment "this.someMethod = function() { /*etc*/ }". In 
	JavaScript, every time you evaluate a function expression, you get a new object. You can tell it's a new object because 
	of "==="; you can also mutate it: it's mutable. So you can set a certain property on it that would not show up on any other 
	instances -- "someMethod". You'd say "new ClosurePattern()" and assign that to x, and also set y to "new ClosurePattern()". 
	Now you've got two instances. x.someMethod !== y.someMethod, and "x.someMethod.foo = 42" would not cause 42 to appear on 
	y.someMethod: they'd be different objects. That hurts! If you do a million constructions, you've got not just a million 
	instances of the ClosurePattern object, you've got a million "someMethod"s inside it.
</blockquote>
<br/>
<p>
	Unless I was creating an application that requires creating millions of JavaScript objects, I would still recommend the Closure
	Pattern for code re-use.
</p>]]></content:encoded>
			<wfw:commentRss>http://scriptble.com/2011/02/closure-versus-prototypal-object-creation/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Writing and Updating DOM Elements in a Frame</title>
		<link>http://scriptble.com/2011/02/writing-and-updating-dom-elements-in-a-frame/</link>
		<comments>http://scriptble.com/2011/02/writing-and-updating-dom-elements-in-a-frame/#comments</comments>
		<pubDate>Thu, 17 Feb 2011 00:30:45 +0000</pubDate>
		<dc:creator>JC Fant IV</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[HTML]]></category>

		<guid isPermaLink="false">http://scriptble.com/?p=158</guid>
		<description><![CDATA[Handling writing and updating objects in an iframe can be bothersome in most browsers. Sure things like jQuery tend to help, but not always. A normal way to access a frame in jQuery is below: $("#FRAME").contents() Now, lets say you actually want to get another element inside of the frame, lets get the HEAD element. [...]]]></description>
			<content:encoded><![CDATA[<p>Handling writing and updating objects in an iframe can be bothersome in most browsers. Sure things like jQuery tend to help, but not always.</p>

<p>A normal way to access a frame in jQuery is below:</p>

<code class="language-javascript">
	$("#FRAME").contents()
</code>
<br/>

<p>Now, lets say you actually want to get another element inside of the frame, lets get the HEAD element.</p>

<code class="language-javascript">
	$("#FRAME").contents().find("HEAD");
</code>
<br/>
<span id="more-158"></span>
<p>Awesome, we now have the head element of the document in the frame. Lets add a style tag to it.</p>

<code class="language-javascript">
	$("#FRAME").contents().find("HEAD").append('<style type="text/css">BODY { background-color: green; }</style>');
</code>
<br/>

<p>Now this worked in most browsers... I say most for a reason. This was an actual use case I was trying to accomplish. However, good ole' IE wouldn't let me actually add a DOM element 
anywhere in the frame. The only thing I was able to do was to add in style tags on the elements. So how did I get around it?</p>

<code class="language-javascript">
	var ifrm;
		
	function addElementToFrame(newStyle) {
		if (typeof ifrm == "undefined"){
			ifrm = document.getElementById('previewFrame');
			if (ifrm.contentWindow){
				ifrm = ifrm.contentWindow;
			}else{
				if (ifrm.contentDocument.document){
					ifrm = ifrm.contentDocument.document;
				}else{
					ifrm = ifrm.contentDocument;
				}
			}
		}
		
		/*
		 * Now that we have the document, lets add a new style tag
		 */
		$("HEAD", ifrm.document).append("<style id='tempTag'>" + newStyle + "</style>");
		
	}
</code>
<br/>

<p>Wow, interesting mix of using straight JavaScript and jQuery in there. However, what happens when I want to just update the same style tag with something new?</p>

<code class="language-javascript">
	var ifrm;
		
	function addElementToFrame(newStyle) {
		if (typeof ifrm == "undefined"){
			ifrm = document.getElementById('previewFrame');
			if (ifrm.contentWindow){
				ifrm = ifrm.contentWindow;
			}else{
				if (ifrm.contentDocument.document){
					ifrm = ifrm.contentDocument.document;
				}else{
					ifrm = ifrm.contentDocument;
				}
			}
		}
		
		/*
		 * Now that we have the document, look for an existing style tag
		 */
		var tag = ifrm.document.getElementById("tempTag");
		
		/*
		 * Hmm, this doesn't look right, but it is. IE will not allow you 
		 * to use a pre-existing style tag and set the innerHTML for that 
		 * element. Which means, we can't create the style tag in another
		 * function and pass back the element and then set the innerHTML 
		 * to what we need. Plus, with this limitation, now we need to 
		 * actually remove the style element from the DOM and recreate 
		 * it each time. LAME.
		 */
		if (typeof tag != "undefined" || tag != null){
			$("#tempTag", ifrm.document).remove();
		}
		
		/*
		 * We only have one shot at writing out the style tag, we must 
		 * include the css at that point as well or IE will bail with an
		 * unsuported method exception.
		 *
		 * add a new style tag
		 */
		$("HEAD", ifrm.document).append("<style id='tempTag'>" + newStyle + "</style>");
	}
</code>
<br/>

<p>And that is how you can add new elements to a DOM in an iframe inside of your page.</p>
]]></content:encoded>
			<wfw:commentRss>http://scriptble.com/2011/02/writing-and-updating-dom-elements-in-a-frame/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Expanding the jQuery Plugin Development Pattern</title>
		<link>http://scriptble.com/2011/02/expanding-the-jquery-plugin-development-pattern/</link>
		<comments>http://scriptble.com/2011/02/expanding-the-jquery-plugin-development-pattern/#comments</comments>
		<pubDate>Tue, 15 Feb 2011 01:00:25 +0000</pubDate>
		<dc:creator>JC Fant IV</dc:creator>
				<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://scriptble.com/?p=151</guid>
		<description><![CDATA[Doing research on a recent project, I came across an article by Mike Alsup on a "jQuery Plugin Development Pattern". If you haven't seen it already its worth a trip to learningjquery.com to checkout the implementation of his pattern. "There are a few requirements that I feel this pattern handles nicely:" Claim only a single [...]]]></description>
			<content:encoded><![CDATA[<p>
	Doing research on a recent project, I came across an article by Mike Alsup on a <a href="http://www.learningjquery.com/2007/10/a-plugin-development-pattern">"jQuery Plugin Development Pattern"</a>. 
	If you haven't seen it already its worth a trip to learningjquery.com to checkout the implementation of his pattern.
</p>

<blockquote>
"There are a few requirements that I feel this pattern handles nicely:"

<ol>
   <li>Claim only a single name in the jQuery namespace</li>
   <li>Accept an options argument to control plugin behavior</li>
   <li>-Provide public access to default plugin settings-</li>
   <li>Provide public access to secondary functions (as applicable)</li>
   <li>Keep private functions private</li>
   <li>Support the Metadata Plugin</li>
   <li>Allow for extending the object via callbacks (either hooks or events) as applicable</li>
   <li>Scope all selectors with the 'this' object</li>
</ol>

</blockquote>
<br/>
<span id="more-151"></span>
<p>
	This is a great start to "authoring a jQuery plugin":http://docs.jquery.com/Plugins/Authoring. However, there are a couple more requirements that I would propse adding in.
</p>

<ol>
   <li>Claim only a single name in the jQuery namespace</li>
   <li>Accept an options argument to control plugin behavior</li>
   <li>-Provide public access to default plugin settings-</li>
   <li>Provide public access to secondary functions (as applicable)</li>
   <li>Keep private functions private</li>
   <li>Support the Metadata Plugin</li>
   <li>**Allow for extending the object via callbacks (either hooks or events) as applicable**</li>
   <li>**Scope all selectors with the 'this' object**</li>
</ol>

<br/>
<p>
	So lets take a look at how we can implement this pattern using a tab plugin.
</p>

<br/>
<h4>Claim Only a single name in the jQuery namespace</h4>
<br/>
<p>
	Setting up a new plugin is pretty simple. First we need to add the plugin name to the jQuery.fn namespace.
</p>

<code class="language-javascript">
	;(function($){
	})(jQuery);
</code>
<br/>
<p>
	Notice that We scope the setup of this plugin inside of an anonymous function that executes with the jQuery parameter as $. We do this so that the jQuery namespace can be changed in order to play well with other 
	javascript frameworks. It also allows us to scope jQuery to $ incase the namespace has already been changed.
</p>

<p>
	Next we need to setup the single namespace for our plugin.
</p>

<code class="language-javascript">
	;(function($){
	    $.fn.tabs = function(tabOptions) {
	        // support mutltiple elements
	        if (this.length > 1){
	            this.each(function() { $(this).tabs(tabOptions) });
	            return this;
			}
        }
	})(jQuery);
</code>
<br/>
<p>
	Notice we setup the name of our plugin into the jQuery.fn namespace. Also, we add in a bit of trickery.  We need to make sure that if this plugin is called on multiple DOM elements, that it will still function properly. 
	We do this by looping through each of the elements and calling .carousel() on them. We then return "this" in order to allow chaining of methods.
</p>

<code class="language-javascript">
        // support mutltiple elements
        if (this.length > 1){
            this.each(function() { $(this).tabs(tabOptions) });
            return this;
		}
</code>
<br/>

<h4>Accept an options argument to control plugin behavior</h4>
<br/>
<p>
	By creating an options argument, we can allow the users to expand/change the default behavior of the plugin. The following code adds in a newOptions parameter and then uses jQuerys 
	built in $.extend to override the default plugin options.
</p>

<code class="language-javascript">
	;(function($){
    $.fn.tabs = function(tabOptions) {
        // support mutltiple elements
        if (this.length > 1){
            this.each(function() { $(this).tabs(tabOptions) });
            return this;
        }

        // SETUP private variabls;
        var tabs = this;

        // setup options
        var defaultOptions = {
								//default options go here.
                                };
								
        var options = $.extend({}, defaultOptions, tabOptions);

        return this;
    }
})(jQuery);

</code>
<br/>
<p>
	Notice the following code it expands the default options:
</p>

<code class="language-javascript">
        var options = $.extend({}, defaultOptions, tabOptions);
</code>
<br/>

<h4>Provide public access to secondary functions (as applicable)</h4>
<br/>
<p>
	We can give access to public functions by attching the functions to the magic variable "this". 
</p>

<code class="language-javascript">
	;(function($){
	    $.fn.tabs = function(tabOptions) {
	        // support mutltiple elements
	        if (this.length > 1){
	            this.each(function() { $(this).tabs(tabOptions) });
	            return this;
	        }
	
	        // SETUP private variabls;
	        var tabs = this;
	
	        // setup options
	        var defaultOptions = {
	                                    debug : false
	                                };
	        var options = $.extend({}, defaultOptions, tabOptions);


			// PUBLIC functions
	        this.changeTab = function() {
	            // change Tab
	        };
	
	        this.getOptions = function() {
	            return options;
	        };

	
	        return this;
	    }
	})(jQuery);

</code>
<br/>

<h4>Keep private functions private</h4>
<br/>
<p>
	Private functions setup in the way below can only be called from within the scope that they were created. What this means is that there is no outside access to these functions. They can only be called 
	from within another public methods or another private methods. In order to access this data we would need to setup public methods to call these private methods.
</p>

<code class="language-javascript">
	;(function($){
	    $.fn.tabs = function(tabOptions) {
	        // support mutltiple elements
	        if (this.length > 1){
	            this.each(function() { $(this).tabs(tabOptions) });
	            return this;
	        }
	
	        // SETUP private variabls;
	        var tabs = this;
	
	        // setup options
	        var defaultOptions = {
	                                    debug : false
	                                };
	        var options = $.extend({}, defaultOptions, tabOptions);

	        // SETUP private functions;
	        var intialize = function() {
					return tabs;
	        };
			
	        var findTabs = function() {
	                                // do something .
	                            };
								
			var selectTab = function(element, tabCSS, selectedClass){
									// do something .
								};
								
	        var hooks = function() {
	                                // do something .
	                            };
			
			// PUBLIC functions
	        this.changeTab = function() {
	            // change Tab
	        };
	
	        this.getOptions = function() {
	            return options;
	        };
	
	        return intialize();
	    }
	})(jQuery);

</code>
<br/>


<h4>Support the Metadata Plugin</h4>
<br/>
<p>Supporting the Metadata plugin is fairly trivial. We test for the existence of the plugin and then add the data that would be attached to the element.</p>

<code class="language-javascript">
	;(function($){
	    $.fn.tabs = function(tabOptions) {
	        // support mutltiple elements
	        if (this.length > 1){
	            this.each(function() { $(this).tabs(tabOptions) });
	            return this;
	        }
	
	        // SETUP private variabls;
	        var tabs = this;
	
	        // setup options
	        var defaultOptions = {
	                                    debug : false
	                                };
	        var options = $.extend({}, defaultOptions, tabOptions);

	        // SETUP private functions;
	        var intialize = function() {
	                // support MetaData plugin
	                if ($.meta){
	                    options = $.extend({}, options, this.data());
	                }

					return tabs;
	        };
			
	        var findTabs = function() {
	                                // do something .
	                            };
								
			var selectTab = function(element, tabCSS, selectedClass){
									// do something .
								};
								
	        var hooks = function() {
	                                // do something .
	                            };
			
			// PUBLIC functions
	        this.changeTab = function() {
	            // change Tab
	        };
	
	        this.getOptions = function() {
	            return options;
	        };
	
	        return intialize();
	    }
	})(jQuery);

</code>
<br/>
<h4>Allow for extending the object via callbacks (either hooks and/or events)</h4>
<br/>
<p>
	In order to do this, lets take a more in depth look at the changeTab function. 
	It sounds complicated, however its a trivial task to setup and allow the moveSlider functionality to be altered by the external options.
</p>

<code class="language-javascript">
	// PUBLIC functions
    this.changeTab = function() {
        // change Tab
    };
</code>
<br/>

<p>In order to alter the behavior we need to allow the user to pass in some options.</p>

<code class="language-javascript">
    // setup options
    var defaultOptions = {
								beforeLoad : function() {
												// do something .
											},
								afterLoad : function() {
												// do something .
											},
                                debug : false
                            };
</code>
<br/>
<p>Now, lets update hooks function to see what needs to be done in order to call the function.</p>

<code class="language-javascript">	   
        var hooks = function(thisObject, hookList, triggerName){
            $(presentation).trigger(triggerName, thisObject);
            if ($.isFunction(hookList)){
                return hookList.apply(thisObject, []).isOK;
            } else if ($.isArray(hookList)) {
                var result = {
                    isOK: true
                };
                for (var i = 0; i < hookList.length; i++) {
                    if (result.isOK) {
                        result = hookList[i].apply(thisObject, [ result.data ]);
                    }
                }
                return result.isOK;
            }else{
                return true;
            }
        }
</code>
<br/>
<p>What exactly is this doing? First of all the hooks function takes 3 parameters. thisObject is equal to the object that you want the callback function to have "this" set to, 
a method to call back on called hookList and the name of the event to be triggered. The reason we call it list, is that we will check to see if hookList is an array of 
functions or just a single function. The following call passes in the tabs object and the onstart callbacks.</p>

<p>Now, lets change the this.changeTab to make use of the beforeLoad and afterLoad events.</p>


<code class="language-javascript">
	this.changeTab = function(element){
		if (hooks(tabs, options.beforeLoad, "beforeLoad")){
			selectTab(element, options.tabsClass, options.tabsSelected);
			
			var tabOptions = {};
			if (options['tab' + tabs.mainTab] != undefined) {
				tabOptions = options['tab' + tabs.mainTab];
			}
			
			$(options.tabPanels, this).hide();
			
			if (options.afterLoad != undefined) {
				hooks(tabs, options.afterLoad, "afterLoad")
			} else {
				$('.tab' + tabs.mainTab, this).show();
			}
		}
	};
</code>
<br/>

<p>In the hooks method we use the .apply in order to pass "this" as the plugin to the next function. They will have access to all of the public methods that are on that instance of the tabs plugin.</p>


<h4>Scope all selectors with the 'this' object</h4>
<br/>
<p>This is actually really simple, but will control the scope of the objects returned by jQuery. Without this, you may clobber another widget on the page or jump outside of the element you are working on. 
Lets take another look at the selectTab method and see how we can scope our selectors.</p>

<code class="language-javascript">
         var selectTab = function(element, tabCSS, selectedClass){
              var selectedTab = 0;
              selectedClass = selectedClass.replace(/^./, "");
              $(tabCSS).each(function(){
                   if (this == element) {
                        tabs.mainTab = selectedTab;
                        $(element).addClass(selectedClass);
                   } else {
                        $(this).removeClass(selectedClass);
                   }
                   selectedTab++;
              });
         };

</code>
<br/>
<p>On the surface, there is nothing wrong with this. However, what happens if we have two different tab groups on the page? Nothing? How about an extremely large DOM? Would this slow down? Yes, actually it would 
and you may or may not be acting on a set of tabs that aren't your own.</p>

<p>So how do we fix this?</p>

<code class="language-javascript">
         var selectTab = function(element, tabCSS, selectedClass){
              var selectedTab = 0;
              selectedClass = selectedClass.replace(/^./, "");
              $(tabCSS, tabs).each(function(){
                   if (this == element) {
                        tabs.mainTab = selectedTab;
                        $(element).addClass(selectedClass);
                   } else {
                        $(this).removeClass(selectedClass);
                   }
                   selectedTab++;
              });
         };
</code>
<br/>
<p>Wait, that is the same code? Close, but look closer at the $(tabCSS) selector. Notice, we now use $(tabCSS, tabs). (<a href="/2011/02/the-great-assumption-javascript/">You could also use $(tabs).find(tabCSS); is faster in most browsers</a>). 
This limits the scope of the search for the tabs and it won't clobber any other tab widgets on the page.</p>
]]></content:encoded>
			<wfw:commentRss>http://scriptble.com/2011/02/expanding-the-jquery-plugin-development-pattern/feed/</wfw:commentRss>
		<slash:comments>19</slash:comments>
		</item>
	</channel>
</rss>
<!-- This Quick Cache file was built for (  scriptble.com/author/jcfant/feed/ ) in 0.61272 seconds, on Feb 5th, 2012 at 6:26 pm UTC. -->
<!-- This Quick Cache file will automatically expire ( and be re-built automatically ) on Feb 5th, 2012 at 7:26 pm UTC -->
