Dynamically load jquery

I work in a really distorted environment in which I cannot deal with this problem using the presentation logic of the MVC framework (CakePHP) I use. This can happen because I have to load this piece of code inside the page where the jQuery script is already loaded.

If I just load jQuery into my piece of code, it works as long as there are no other jQuery scripts. When there are 2 scripts, it does not work and says $ is not a function . Not quite sure how this works, but explanations may help.

In any case, I have to dynamically load the script into the page.

So this is my code:

 <script id="loadjq" type="text/javascript"></script> <script id="loadcloud" type="text/javascript"></script> <script type="text/javascript"> if(typeof jQuery=="undefined"){ document.getElementById('loadjq').src= 'http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js'; } document.getElementById('loadcloud').src= '/js/jqcloud.js'; $(document).ready(function(){ $("#tagcloud").jQCloud(word_list,{}); }); </script> 

Loads a script, but when I try to load jqcloud.js, it cannot find another script, possibly because it starts before another script loads. With a few dirty tricks, I could go through this, but the same problem occurs when I reach $(document).ready(function()

Is there a clean way to do this? I need it to wait for the previous scripts to load before executing, or at least what the problem looks like. Not quite sure if this is really my problem.

+4
source share
1 answer

How about installing event handlers in a jquery script element to call a jqcloud script when the download is complete. Sort of

 if(typeof jQuery=="undefined"){ var loadjqScript = document.getElementById('loadjq').src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js'; // Code below handles browser that support script onload // and ones that don't var loadFunction = function() { if (this.readyState == 'complete' || this.readyState == 'loaded') { loadJqCloud(); } }; loadjqScript.onreadystatechange = loadFunction; loadjqScript.onload = loadJqCloud; } function loadJqCloud() { document.getElementById('loadcloud').src= '/js/jqcloud.js' } 
+4
source

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


All Articles