Upload jQuery to another js file

I have a javascript file that also uses jQuery. To download it, I wrote this code:

function include(filename) { var head = document.getElementsByTagName('head')[0]; var script = document.createElement('script'); script.src = filename; script.type = 'text/javascript'; head.appendChild(script) } include('http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js'); alert("1"); $(document).read(function(){}); alert("2"); 

This fires alert("1") , but the second alert does not work. When I check the elements, I see an error saying that $ is undefined.

How do I solve this problem?

+6
source share
2 answers

You need to execute any specific jQuery code only after loading the script, which, obviously, can happen at a much later point in time after adding it to the section of the chapter:

 function include(filename, onload) { var head = document.getElementsByTagName('head')[0]; var script = document.createElement('script'); script.src = filename; script.type = 'text/javascript'; script.onload = script.onreadystatechange = function() { if (script.readyState) { if (script.readyState === 'complete' || script.readyState === 'loaded') { script.onreadystatechange = null; onload(); } } else { onload(); } }; head.appendChild(script); } include('http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js', function() { $(document).ready(function() { alert('the DOM is ready'); }); }); 

And here is a live demonstration .

You can also see script loaders, such as yepnope or RequireJS , which make this task easier.

+21
source

The problem here is probably that although you include the script, this does not mean that it loads when you try to make $(document).ready(function(){}); . You can look in Google Loader to prevent this problem. http://code.google.com/intl/fr-FR/apis/loader/

-1
source

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


All Articles