How to defer javascript
<p>I am using the fancybox jquery plugin and I am trying to defer the javascript to the end of page loading</p>

<pre><code>    &lt;html&gt;
    &lt;head&gt;
    &lt;/head&gt;
    &lt;body&gt; 
        content
/*bottom of body*/
        &lt;script src="jquery-1.8.3.min.js" type="text/javascript"&gt;&lt;/script&gt;
        &lt;script type="text/javascript" src="jquery.fancybox-1.3.4/fancybox/jquery.fancybox-1.3.4.pack.js" &gt;&lt;/script&gt;
        &lt;script type="text/javascript"&gt;
            $(document).ready(function() {
                $(".example3").fancybox({
                    'transitionIn'  : 'none',
                    'transitionOut' : 'none'    
                });
            });
        &lt;/script&gt;
    &lt;/body&gt;
    &lt;/html&gt;
</code></pre>

<p>At this point the plugin works but the javascript is not deferred. Then I change the script to</p>

<pre><code>&lt;script defer="defer" type="text/javascript"&gt;
    window.onload=function(){
        var mycode;
        mycode=document.createElement("script");
        mycode.type="text/javascript";
        mycode.src="jquery.fancybox-1.3.4/fancybox/jquery.fancybox-1.3.4.pack.js";
        document.getElementsByTagName("head")[0].appendChild(mycode);
    }
&lt;/script&gt;
</code></pre>

<p>like I read <a href="http://www.webpagetest.org/forums/showthread.php?tid=7897" rel="nofollow">here</a>, but then the plugin sometimes work, sometimes it doesn't work. According to google pagespeed I still need to defer the jquery-1.8.3.min.js script. If I defer it the same way, google pagespeed seems ok with it, but then the plugin doesn't work at all.</p>

<p>How am I supposed to do this?</p>

<p><strong>Complete solution based on Jamed Donnelly's answer:</strong></p>

<p>I removed all .js scripts from the head. Then I added this just before the  tag:</p>

<pre><code>&lt;script&gt;
(function() {
    function getScript(url,success){
        var script=document.createElement('script');
        script.src=url;
        var head=document.getElementsByTagName('head')[0],
        done=false;
        script.onload=script.onreadystatechange = function(){
        if ( !done &amp;&amp; (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete') ) {
            done=true;
            success();
            script.onload = script.onreadystatechange = null;
            head.removeChild(script);
        }
        };
        head.appendChild(script);
    }

getScript("jquery-1.8.3.min.js",function(){
    getScript("jquery.fancybox-1.3.4/fancybox/jquery.fancybox-1.3.4.pack.js", function() {});
    getScript("myCustomScript.js", function() {});
});

})();
&lt;/script&gt;
</code></pre>

<p>I created a file myCustomScript.js:</p>

<pre><code>$(document).ready(function(){ 
    $(".example3").fancybox({
        'transitionIn'  : 'none',
        'transitionOut' : 'none'    
    });
});
</code></pre>

<p>And that's all.</p>
