Loading scripts after page load?

后端 未结 7 1628
粉色の甜心
粉色の甜心 2020-11-27 15:16

I work with an advertising company, where we tag certain pages to track activity. A client of mine wants to fire off a javascript tag to track activity AFTER the page has fi

7条回答
  •  醉梦人生
    2020-11-27 15:29

    So, there's no way that this works:

    window.onload = function(){
      
    };
    

    You can't freely drop HTML into the middle of javascript.


    If you have jQuery, you can just use:

    $.getScript("http://jact.atdmt.com/jaction/JavaScriptTest")
    

    whenever you want. If you want to make sure the document has finished loading, you can do this:

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

    In plain javascript, you can load a script dynamically at any time you want to like this:

    var tag = document.createElement("script");
    tag.src = "http://jact.atdmt.com/jaction/JavaScriptTest";
    document.getElementsByTagName("head")[0].appendChild(tag);
    

提交回复
热议问题