简体   繁体   中英

How to load a js file after loading html?

After i load this :

$('#buy-div').load('../buyBar/buyBar.html',function() {
 //do some things here
 });

I would like to include this :

<script src="../buyBar/BuyBar.js"></script> //access some html that does not exist

Beacuse in this js i am looking for some html that does not exist only after the .load function is done. (such as getElementById or $('input').keyup(function() { that happens before the .load was finished.

Just put the code that you want to run after the html is loaded in a function. Then call that function in the callback function of the .load('../buyBar/buyBar.html')

Assume "../buyBar/BuyBar.js" originally contains

document.getElementByID("#someElement").innerHTML = "...";

You can change it to

function someFunction(){document.getElementByID("#someElement").innerHTML = "...";}

Now just put <script src="../buyBar/BuyBar.js"></script> in the <head> as usual. Then do this:

$('#buy-div').load('../buyBar/buyBar.html',function() {
    someFunction();
    //do other stuff   
});

I figure out i can do it by loading it when .load is done :

     let script = document.createElement('script');
      script.src = "../buyBar/Pay.js";
      document.body.append(script);  

This works but i am not sure is the best solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM