Enable jQuery if it is not enabled

I want to include jquery in a file if it is not already included on the page. How can i do this?

I wrote this, but it gives an undesirable conclusion.

<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> 
+7
source share
5 answers

You cannot do this in PHP. Try this instead

 <script type="text/javascript"> if(typeof jQuery == 'undefined'){ document.write('<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js"></'+'script>'); } </script> 
+11
source
 <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> 
+9
source

You can try the following:

 <script>window.jQuery || document.write('<script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js"><\/script>')</script> 
+6
source

Your PHP runs on the server and prints some text.

The browser then interprets this text as HTML and JavaScript.

You cannot run PHP on the server, in a document that it has already sent to the browser, in response to the logic running in the browser.

You either need this completely in JavaScript, or, more safely, parse the server-side logic so that you keep track of whether jQuery is enabled or not.

+4
source

If you want to do this with PHP, which I think is better, you can do it

  • Before calling the load () function, create a variable of the type:

    var load_script = 'no';

  • The load () function accepts an optional parameter that you can use to send data to the server. Use it to publish the load_script variable created earlier, for example

    $ ('# receiver_div') load ('mypage.html', {'load_script': load_script}., ​​Function (HTML) {

    // material to be done after loading the page

    })

  • Then on the page you are loading, catch a published value like this

    $ load_script = $ _POST ('load_script');

  • Then you can make an if statement to exclude the script you need, for example

if ($ load_script! = 'no') {

echo "<script src="jquery.js"></script>" ;

}

0
source

All Articles