在加载脚本后调用 javascript 函数

我有一个 html 页面,在这个页面中,我通过一个 javascript 动态地追加 html,如下所示

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

我想调用一个 js 函数,例如 loadedContent () ; 一旦上面的脚本添加了动态 html。

有人能告诉我怎么做吗?

137664 次浏览

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)

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

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

If you're reading this post in 2021, probably you're more used to Promises. A more modern approach is preferable if either all your target browsers support ES6 or you are using a polyfill.

This solution works like @JaykeshPatel answer, but it's based on Promises:

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

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


// use
loadScript('http://your-cdn/jquery.js')
.then(() => {
console.log('Script loaded!');
})
.catch(() => {
console.error('Script loading failed! Handle this error');
});

You can pass some contextual variables in arguments of the res callback, or if your library imported some global symbol, you can reference it there.

For example, since jQuery introduces the $ global symbol, you can call res($) and create a local scope for it (perfect if you are using TypeScript and you don't want to declare a module variable in each file, in this way you can write const $ = await loadScript(..)).

If you don't mean to pass any argument, you can just shorten your code like this:

script.onload = res;
script.onerror = rej;
  $.getScript("your script",function () {
"your action";
});

This is all you need

await new Promise((resolve) => {
let script = document.createElement("script");


script.onload = () => {
resolve();
};


script.src = "https://example.net/app.js";


document.head.appendChild(script);
});