Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading scripts after page load?

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,

like image 440
Kamui Avatar asked Nov 01 '13 23:11

Kamui


People also ask

How do you load a script after Page load react js?

We start by creating an empty <script></script> tag in the memory as script and then assign the necessary attributes to its src and the id to identify the script later. Finally, we append the script to our <body></body> tag to actually load this.


1 Answers

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); 
like image 85
jfriend00 Avatar answered Oct 07 '22 19:10

jfriend00