<?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>Web-developer notepad</title>
	<atom:link href="http://slicezilla.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://slicezilla.com</link>
	<description>know-how, researches, code snippets</description>
	<lastBuildDate>Sat, 12 Nov 2011 15:53:44 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Load jQuery on demand</title>
		<link>http://slicezilla.com/2011/11/12/load-jquery-on-demand/</link>
		<comments>http://slicezilla.com/2011/11/12/load-jquery-on-demand/#comments</comments>
		<pubDate>Sat, 12 Nov 2011 14:07:26 +0000</pubDate>
		<dc:creator>slicezilla</dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[jquery]]></category>

		<guid isPermaLink="false">http://slicezilla.com/?p=9</guid>
		<description><![CDATA[In order to load jQuery on demand you can use loadJquery.js script. Quick start Download script, edit its bottom part after words &#8220;PUT YOUR CODE HERE&#8221;, this one: (function () { ... /* -------------------- PUT YOUR CODE HERE ------------------ */ &#8230;<p class="read-more"><a href="http://slicezilla.com/2011/11/12/load-jquery-on-demand/">Read more &#187;</a></p>]]></description>
			<content:encoded><![CDATA[<p>In order to load jQuery on demand you can use <a href="http://slicezilla.com/js/loadJquery.js">loadJquery.js</a> script.</p>
<h2>Quick start</h2>
<p>Download script, edit its bottom part after words &#8220;PUT YOUR CODE HERE&#8221;, this one:</p>
<pre class="wp-code-highlight prettyprint">(function () {

...

    /* -------------------- PUT YOUR CODE HERE ------------------ */
    loadJquery({
        url: 'http://code.jquery.com/jquery-latest.min.js',
        timeout: 5000, //ms
        success: function ($) {
            $('h1').css('border', '2px solid red');
        },
        error: function () {
            alert(&quot;Can't load jQuery.&quot;);
        }
    });
}());</pre>
<h2>Advantages:</h2>
<ul>
<li>based on jquery 1.7.2, so should be stable and cross-browser</li>
<li>exceptions handled with help of try/catch</li>
<li>ability to set download timeout</li>
<li>jQuery will not be loaded, if found in page</li>
<li>simplicity for end-user: just write your code in success/error callbacks</li>
<li>no conflicts with other javascript libraries like prototype.js</li>
<li>script passes jslint-validation</li>
</ul>
<p>Now bit more information for those who interested.<br />
Script consists of two parts: loadScript и loadJquery.</p>
<h2>loadScript</h2>
<p>The function almost completely based on jQuery 1.7.2, which is latest at the moment.<br />
External script is loading by putting SCRIPT tag into HEAD.<br />
Exceptions are handled with try/catch, in theory javascript-erorrs, if any, should be catched without placing error in browser console.<br />
There is possibility to setup download timeout. If timeout reached, download will be stopped and error-callback will be called.</p>
<p>Example of using:</p>
<pre class="wp-code-highlight prettyprint">loadScript({
    url: 'http://example.com/script.js', //script url
    timeout: 5000, //optional timeout in ms
    success: function () {
        alert('Script loaded callback.');
    },
    error: function () {
        alert('Script was not loaded.');
    }
});</pre>
<h2>loadJquery</h2>
<p>Few details about this function:</p>
<ul>
<li>jQuery will not be loaded, if found in page</li>
<li>.noConflict() used, so end-user should not worry about conflicts with other javascript library like prototype.js</li>
</ul>
<h2>Full listing of the script.</h2>
<pre class="wp-code-highlight prettyprint">/*!
 *
 * loadJquery.js
 * Load jQuery on demand from javascript
 * Author: contact@slicezilla.com
 * November 2011
 *
 * The script uses part of jQuery JavaScript Library v1.7
 * http://jquery.com/
 * Copyright 2011, John Resig
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
*/
/*global document, setTimeout, clearTimeout, alert, jQuery*/
(function () {
    &quot;use strict&quot;;
    var loadScript = function (options) {
        var script, transportTimeout,
            head = document.head || document.getElementsByTagName('head')[0] || document.documentElement,
            transport = {
                send: function (url, successCallback) {

                    script = document.createElement('script');

                    script.async = 'async';
                    script.src = url;

                    // Attach handlers for all browsers
                    script.onload = script.onreadystatechange = function (event, isAbort) {
                        if (isAbort || !script.readyState || /loaded|complete/.test(script.readyState)) {

                            // Handle memory leak in IE
                            script.onload = script.onreadystatechange = null;

                            // Remove the script
                            if (head &amp;&amp; script.parentNode) {
                                head.removeChild(script);
                            }

                            // Dereference the script
                            script = undefined;

                            //callback if not abort
                            if (!isAbort &amp;&amp; typeof successCallback === 'function') {
                                clearTimeout(transportTimeout);
                                successCallback();
                            }
                        }
                    };
                    // Use insertBefore instead of appendChild  to circumvent an IE6 bug.
                    // This arises when a base node is used (#2709 and #4378).
                    head.insertBefore(script, head.firstChild);
                    //head.appendChild(script);
                },

                abort: function (errorCallback) {
                    clearTimeout(transportTimeout);
                    if (script) {
                        script.onload(0, 1);
                    }
                    if (typeof errorCallback === 'function') {
                        errorCallback();
                    }
                }
            };

        //init timeout
        if (options.timeout &gt; 0) {
            transportTimeout = setTimeout(function () {
                transport.abort(options.error);
            }, options.timeout);
        }

        //get script
        try {
            transport.send(options.url, options.success);
        } catch (e) {
            transport.abort(options.error);
        }
    };

    //function which will load jQuery using loadScript
    function loadJquery(options) {
        if (typeof jQuery !== 'undefined') {
            //jQuery is loaded already, just perform business logic
            if (typeof options.success === 'function') {
                //pass jQuery as parameter, in order to have $ === jQuery in callback
                //just in case that $.noConflict was used already, and $ !== jQuery
                jQuery(options.success);
            }
        } else {
            //jQuery was not loaded on a page
            loadScript({
                url: options.url,
                timeout: options.timeout,
                success: function () {
                    jQuery.noConflict();
                    if (typeof options.success === 'function') {
                        jQuery(options.success);
                    }
                },
                error: options.error
            });
        }
    }

    /* -------------------- PUT YOUR CODE HERE ------------------ */
    loadJquery({
        url: 'http://code.jquery.com/jquery-latest.min.js',
        timeout: 5000, //ms
        success: function ($) {
            $('h1').css('border', '2px solid red');
        },
        error: function () {
            alert(&quot;Can't load jQuery.&quot;);
        }
    });

}());</pre>
]]></content:encoded>
			<wfw:commentRss>http://slicezilla.com/2011/11/12/load-jquery-on-demand/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
