How to execute jquery callback after loading it?

I load jQuery asynchronously:

function addScript(url) { var script = document.createElement('script'); script.src = url; document.getElementsByTagName('head')[0].appendChild(script); } addScript('jquery.js'); // non-jquery code ... // jquery specific code like: $()... 

As such - how can I call my jQuery specific code after loading jQuery (because, since I load my JavaScript asynch - it does not block, which is good, but it tries to execute my special jQuery code before jQuery is loaded).

+4
source share
4 answers

You can place a copy of the jquery file yourself. Then you can add a callback function call at the bottom of jquery.js:

 /* jquery code goes here ... */ my_onload_callback(); 
+3
source

This works for me (tested in FireFox 33.0.3):

  if(typeof(jQuery) == "undefined"){ //create onload-callback function window["__9384nalksdfalkj04320"] = function(){ console.log("jQuery=" + jQuery); }; //load jQuery asynchronously var script = document.createElement("script"); script.setAttribute("type", "text/javascript"); script.setAttribute("onload", "__9384nalksdfalkj04320();"); //register onload-callback listener function script.setAttribute("src", "http://code.jquery.com/jquery-latest.min.js"); document.head.appendChild(script); } 
+2
source

You can include LabJs on your page (perhaps on every page). On the other hand, you are pasting the script over and over again. LabJs, on the other hand, is quite small - 4k minified - and allows you to handle complex asynchronous cross-browser loading patterns with very simple code, for example:

 <script> // Minified LabJs goes here </script> <script> function init() { // Your code after jquery loads goes here } $LAB .script('//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js') .wait(init); </script> </body> 
+1
source

I am not very good at standard Javascript, but you can try to do something like this:

 var script_object = new addScript('jquery.js'); script_object.onLoad('addScript("my_jquery_related.js")'); 

Admittedly, this is a mega shot in the dark.

If this does not work, perhaps go through your function as a callback variable to your JS loader:

 addScript(url, function(){ function_to_call();}) function addScript(url, call_back_function) { var script = document.createElement('script'); script.src = url; document.getElementsByTagName('head')[0].appendChild(script); call_back_function.call; } addScript('jquery.js'); 

What I got: \

-1
source

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


All Articles