Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call javascript function after script is loaded

I have a html page where I am appending html at dynamically through a javascript like below

<script type="text/javascript" src="/myapp/htmlCode"></script> 

I want to call a js function e.g. loadedContent(); once the above script adds dynamic html.

Can someone help me how I can do that?

like image 369
Neeraj Avatar asked Feb 01 '13 10:02

Neeraj


People also ask

How do I run a function after the page is loaded?

$(window). bind("load", function() { // code here }); This works in all the case. This will trigger only when the entire page is loaded.

How do you trigger a function in JavaScript?

onchange: It is triggered when an HTML element changes. onclick: It is triggered when an HTML element is clicked. onmouseover: It is triggered when the mouse is moved over a HTML element. onmouseout: It is triggered when the mouse is moved out of a HTML element.

What event do you use to perform something after the page has finished loading?

The onload event occurs when an object has been loaded. onload is most often used within the <body> element to execute a script once a web page has completely loaded all content (including images, script files, CSS files, etc.).


2 Answers

you can achieve this without using head.js javascript.

function loadScript( url, callback ) {   var script = document.createElement( "script" )   script.type = "text/javascript";   if(script.readyState) {  // only required for IE <9     script.onreadystatechange = function() {       if ( script.readyState === "loaded" || script.readyState === "complete" ) {         script.onreadystatechange = null;         callback();       }     };   } else {  //Others     script.onload = function() {       callback();     };   }    script.src = url;   document.getElementsByTagName( "head" )[0].appendChild( script ); }   // call the function... loadScript(pathtoscript, function() {   alert('script ready!');  }); 
like image 86
Jaykesh Patel Avatar answered Oct 14 '22 01:10

Jaykesh Patel


I had the same problem... My solution (without jQuery) :

<script onload="loadedContent();" src ="/myapp/myCode.js"  ></script> 
like image 41
Didier68 Avatar answered Oct 14 '22 01:10

Didier68