简体   繁体   中英

How to get a JavaScript file after you have loaded the page?

I want to load a AJAX form into my page with it's own validation.js attached to it. How can I do that?

I tried to load every one with its own $.ajax request, then output the HTML on the page successfully, but the validation.js doesn't work on the form.

Can I load a JavaScript file then a HTML file (with ajax ) in my existing page, then get the HTML output on the page to respond to this JavaScript functions?

use the following javascript for adding a javascript file in async mode after the page has loaded.

(function() {
  var d=document,
  h=d.getElementsByTagName('head')[0],
  s=d.createElement('script');
  s.type='text/javascript';
  s.async=true;
  s.src='/js/myfile.js';
  h.appendChild(s);
}()); 

if you have a number of files to load this way, you can convert this into a function call.

function asyncLoader(scriptName)
{
  var d=document,
  h=d.getElementsByTagName('head')[0],
  s=d.createElement('script');
  s.type='text/javascript';
  s.async=true;
  s.src = scriptName;
  h.appendChild(s);
}

this method does not guarantee/notify when the js file will be loaded. for that you can put some event call in the file which is being loaded.

if you are loading some html from ajax and adding it to a your current html (as innerHtml) you can put the <script> tag inside that html and it will behave same as above code.

see this question and its answers for more details.

EDIT :

following is a JQuery way using $.getScript

$.getScript("path/my_script.js", function(){
  console.log( "Load was performed." );
});  //JQuery can also be used instead of $

doing the same using $.ajax

$.ajax({
  url: "path/my_script.js",
  dataType: "script",
  success: function(){
    console.log( "Load was performed." );
  }
});

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