How Do I Add jQuery To Head With JavaScript?
<p>I am trying to include jQuery to an HTML page conditionally. It only needs to be added if it doesn't exist yet.</p>

<p>I am using the following code near the top of my body tag to inject a script tag that includes the jQuery library in the head.</p>

<pre><code>&lt;script type="text/javascript"&gt;

    if (typeof jQuery === 'undefined') {
        alert('now adding jquery');
        var head = document.getElementsByTagName("head")[0];
        script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js';
        head.appendChild(script);
        if (typeof jQuery === 'undefined') {
            alert('jquery still not present :(');
        }
    } else {
        alert('jquery already present');
    }
&lt;/script&gt;
</code></pre>

<p>When I execute it, I get the message that jQuery is still not present after adding it. The script tag <strong>does</strong> correctly show up in the loaded page's source.</p>

<p>Trying to make use of jQuery a little further down below in my page, confirms that jQuery is indeed not working. As expected, Chrome's JavaScript console says '$ not defined'.</p>

<p>How can I get this to work?</p>
