Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
-5
rated 0 times [  1] [ 6]  / answers: 1 / hits: 191837  / 11 Years ago, fri, november 1, 2013, 12:00:00

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 finished loading entirely (to prevent the page content from loading slowly due to slow tag load times).



An example tag that should load AFTER the page has fully loaded is:



<script>document.write('<s'+'cript language=JavaScript src=http://jact.atdmt.com/jaction/JavaScriptTest></s'+'cript>')</script>


I was looking at some stackoverflow threads and I came across the below implementation which I think will work:



window.onload = function(){
<script language=JavaScript src=http://jact.atdmt.com/jaction/JavaScriptTest></script>
};


I tested this on my own webpage and I did get the tag to fire off, but I'm wondering if there are any alternate or more robust methods, ideally using jquery of some kind.



Below is a sample implementation that the client tried, but it seems to break their page:



<script>
jQuery(window).load(function () {$('<script language=JavaScript src=http://jact.atdmt.com/jaction/JavaScriptTest></script>').insertAfter('#div_name');});
</script>


I haven't done JQuery in a while and was hoping I could get some input from other members here. Is there any other way I can call the above script after page load using JQuery?



Thanks,


More From » jquery

 Answers
37

So, there's no way that this works:



window.onload = function(){
<script language=JavaScript src=http://jact.atdmt.com/jaction/JavaScriptTest></script>
};


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);

[#74552] Thursday, October 31, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
danae

Total Points: 26
Total Questions: 97
Total Answers: 112

Location: Oman
Member since Wed, Apr 12, 2023
1 Year ago
;