How to dynamically load Javascript files and use them immediately?

I am using jQuery to dynamically add script tags in the body tab of a web page. I got something like:

function addJS(url) {
  $("body").append('<script type="text/javascript" src='+url+'></script>'); 
}

I add a few scripts this way and try to use them right after. EG:

lib.js

function core() {...}
alert("I'am here !");

init.js

addJS("lib.js");
c = new core();

test.html

<html>
  <head>
    <title>test</title>        
    <script type="text/javascript" src="init.js"></script> 
  </head>
  <body>
     Hello
  </body>
</html>

Downloading test.html pops up "I'm here" and then ends with the error "kernel is not defined". Of course, merging both JS files will allow them to work perfectly.

I just don't get it o_O.

EDIT

I simplified this example, but Jeff's answer made me realize that it was a mistake. So here are some details:

init.js is not in the test.html header when it reloads because I am inserting it with code expressed on a bookmarklet.

So, the real execution process is as follows:

reload test.html > > jquery init.js > lib.js

.

2

( :-)), . ?

+3
5

" ", . , lib.js init.js, " ()" , lib.js .

getScript , script:

$.getScript('lib.js', function() {
    var c = new core();
});
+3

jQuery , getScript.

+5

, addJS body.

, HTML,

c = new core() 

lib.js script ( body).

c = new core(); $(document).ready(function() {...}); script body.

+1

IMO, script script . :

  • script .
  • , script, ( , 404?)

$.getScript(), , script $.ajax() eval().

: eval() , script ! ...

! $.getScript() :)

cheers, jrh.

+1

, : script script. , . , script core(), , lib.js . jQuery , , script .

+1

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


All Articles