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?

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!'); 
});

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

<script onload="loadedContent();" src ="/myapp/myCode.js"  ></script>

try something like this

var script = document.createElement('script');

if(script.readyState) {  //IE
script.onreadystatechange = function() {
  if ( script.readyState === "loaded" || script.readyState === "complete" ) {
    script.onreadystatechange = null;
    alert(jQuery);
  }
};
 } else{//others
script.onload = function() {
  alert(jQuery); 
}
}
script.src = "http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js"
document.documentElement.appendChild(script);

You could set an interval timer, and once the script is loaded, cancel the timer, and do something.

var fileInterval = setInterval(function() {
    if (functionInFile) {
        // do something
        clearInterval(fileInterval); // clear interval
    }
}, 100); // check every 100ms

actually you could just put the loadedContent() as the last line of the script you're loading (which is kind of the concept behind JSONP)


In 2019, maybe a new approach is preferable, if either all your target browsers support ES6 or you are using babel.

The answer of @JaykeshPatel is ok, but here is a more modern solution based on Promise:

// definition
function loadScript(scriptUrl) {
  const script = document.createElement('script');
  script.src = scriptUrl;
  document.body.appendChild(script);

  return new Promise(res => {
    script.onload = function() {
      res();
    }
    script.onerror = function () {
       rej();
    }
  });
}

// use
loadScript('http:// .... /jquery.js')
  .then(() => {
    console.log('Script loaded!');
  });

PS. you can shorten the Promise content in this way:

    script.onload = res;
    script.onerror = rej;

Check out head.js. It will achieve what you're after, providing callbacks when your file(s) have successfully loaded and executed.


My answer is an extension of the Jaykesh Patel answer. I've implemented this code in order to load multiple javascript. Hope this helps someone:

// RECURSIVE LOAD SCRIPTS
function load_scripts( urls, final_callback, index=0 )
{
    if( typeof urls[index+1] === "undefined" )
    {
        load_script( urls[index], final_callback );
    }
    else
    {
        load_script( urls[index], function() {
            load_scripts( urls, final_callback, index+1 );
        } );
    }
}

// LOAD SCRIPT
function load_script( url, callback )
{
    var script = document.createElement( "script" );
    script.type = "text/javascript";
    if(script.readyState) // IE
    {
        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 );
    debug("javascript included: "+url);
}

// EXAMPLE  
var main = function()
{
    console.log("main function executed");
}
var js = [ "path/to/script-1", "path/to/script-2", "path/to/script-3" ];
load_scripts( js, main );

Need Your Help

C#: Alternative to GenericType == null

c# generics null

I need to check a generic object for null, or default(T). But I have a problem... Currently I have done it like this:

LINQ to SQL ForeignKeyReferenceAlreadyHasValueException error

c# linq-to-sql

This error is being generated when I try to change a foreign key.