简体   繁体   中英

How to execute a script tag inside a script returned by jquery function?

One of my clients would like to execute a script after the rest of the page content has fully loaded.

I suggested the following jquery function:

script>

$(window).load(function() {
$.getScript("http://jact.atdmt.com/jaction/JavaScriptTest");
});

</script>

Which calls the script above only after the rest of the page has loaded. However, the script above is also supposed to call another script after it executes. This looks something like the below:

function AT_tags(){
  try{var tags = new Array();
    var imgs = new Array();
    tags = [];
    for(var i=0; i<tags.length; i++)
    { imgs[i] = new Image();
      imgs[i].src = tags[i];}
    this.csk='Test';
  }catch(e){this.csk='Error';}}
var AT_csk = new AT_tags();
document.write('<s'+'cript language="JavaScript" src="http://jact.atdmt.com/jaction/KamuiTag/"></scr'+'ipt>');

The second script - that says jaction/KamuiTag - isn't executing when the first script is called this way.

Can someone please explain to me why a script within a script that executes using the above jquery function would not get called?

Also, does anyone have any fixes or suggestions?

Thanks,

You can use callback for $.getScript() like below;

<script>

$(window).load(function() {
  $.getScript("http://jact.atdmt.com/jaction/JavaScriptTest", function() {
    function AT_tags(){
      try{var tags = new Array();
        var imgs = new Array();
        tags = [];
        for(var i=0; i<tags.length; i++)
        { imgs[i] = new Image();
          imgs[i].src = tags[i];}
        this.csk='Test';
      }catch(e){this.csk='Error';}}
      var AT_csk = new AT_tags();
      $.getScript("http://jact.atdmt.com/jaction/KamuiTag/");
  });
});

</script>

Try using the DOM.

document.head = document.head || document.getElementsByTagName('head')[0];
var js = document.createElement('script');
js.setAttribute('type','text/javascript');
js.setAttribute('src','http://jact.atdmt.com/jaction/KamuiTag/');
document.head.appendChild(js);

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