Download jQuery on the fly

I can’t understand what is wrong with my code here. I am trying to load jQuery dynamically if it is missing from the page.

<head> <script> (function() { if (typeof jQuery != 'undefined') { /* jQuery is already loaded... verify minimum version number of 1.4.2 and reload newer if needed */ if (/1\.(0|1|2|3|4)\.(0|1)/.test(jQuery.fn.jquery) || /^1.1/.test(jQuery.fn.jquery) || /^1.2/.test(jQuery.fn.jquery)|| /^1.3/.test(jQuery.fn.jquery)) { loadJQ(); } } else { loadJQ(); } function loadJQ() { /* adds a link to jQuery to the head, instead of inline, so it validates */ var headElement = document.getElementsByTagName("head")[0]; linkElement=document.createElement("script"); linkElement.src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"; linkElement.type="text/javascript"; headElement.appendChild(linkElement); //alert(headElement); } })(); </script> </head> 

This is my body.

  <body> <button>Click me</button> <script type="text/javascript"> $(document).ready(function(){ alert("hello"); $("button").click(function(){ $(this).hide(); }); }); </script> </body> 

When I put this on my html page, I get the error "$ undefined". Does anyone know why?

+6
source share
3 answers

With the help of a friend of mine, it turned out what was the problem with the above code.

When document.ready is executed, jquery is not on the page (there are two onReady elements) ... and since the addToHead version does not block, the rest of javascript is executed in parallel and not executed.

I added this immediately after running the body tag, and it works great:

 <script type="text/javascript"> if (typeof jQuery == 'undefined') { document.write('<scr'+'ipt type="text/javascript" src="http://ajax.googleapis.com /ajax/libs/jquery/1.7.1/jquery.min.js">'+'</scr'+'ipt>'); } </script> 
0
source

"$ not defined" error means jquery is not loaded.

Try this script download jquery.

http://css-tricks.com/snippets/jquery/load-jquery-only-if-not-present/

+3
source

"$ not defined." Error starting jQuery script code not executing.

You can try using the script attribute to delay code execution until it is loaded by changing the script tag to

  <script type="text/javascript" defer="defer"> 
+2
source

Source: https://habr.com/ru/post/905348/


All Articles