1

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?

0

3 Answers 3

1

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>
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

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

other options are here

1 Comment

Using document.write after the page has loaded will result in the entire page being replaced, so that's bad advice for a button event.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.