开发者

Run Javascript code from external .js file on button click

Here is what i want to do.

Normally we can call javascript functions on different event, button clicks within the page provided that script is already in the page (may be in head section) or it has been loaded in the head section from external js file on load time.开发者_高级运维

Is it possible to load an external js file not when the page loads but at a later stage when (say) a button is clicked.

I know this is easily possible in JQuery:

$.getScript("url to js file", function(){});

But i want to know how can we do the same using simple javascript within the page without JQuery?


Dynamically create the script element :

<script>
var oHead = document.getElementsByTagName('HEAD').item(0);
var oScript= document.createElement("script");
oScript.type = "text/javascript";
oScript.src="other.js";
oHead.appendChild( oScript);
</script>


You do it like this:

var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'helper.js';
head.appendChild(script);


<script language="javascript">
document.write("<script src='other.js'><\/script>");
</script>

other options are here

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜