Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include jQuery, if not included already

I want to include the jquery in file, if not included already in the page. How can I do this?

I wrote this, but it's giving undesired output.

<script type="text/javascript">
if ('undefined' == typeof window.jQuery) {
    // jQuery not present
//  alert("Jquery Unavailable");
<?php echo '<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js"></script>'; ?>
} else {
    // jQuery present
    alert("Jquery Available");
}
</script>
like image 667
Thompson Avatar asked Apr 29 '12 09:04

Thompson


2 Answers

<script type="text/javascript">
    if(typeof jQuery == 'undefined'){
        var oScriptElem = document.createElement("script");
        oScriptElem.type = "text/javascript";
        oScriptElem.src = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js";
        document.head.insertBefore(oScriptElem, document.head.getElementsByTagName("script")[0])
    }
</script>
like image 139
noob Avatar answered Oct 15 '22 03:10

noob


You could try the below:

<script>window.jQuery || document.write('<script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js"><\/script>')</script>
like image 43
px4n Avatar answered Oct 15 '22 02:10

px4n