Link to home
Start Free TrialLog in
Avatar of anAppBuilder
anAppBuilderFlag for United States of America

asked on

Add JavaScript file using a JavaScript function

Is there a way to dynamically add a JavaScript file to a webpage using a JavaScript function?

The method in this link looks promising, but doesn't seem to work: How do I include a Javascript file in a Javascript file?

My code is posted below.  What am I dong wrong?

Of course if I add this line to the HTML file, it will work.  But I am trying to learn a way to do this dynamically.
<script type="text/javascript" src="another.js"></script>

Open in new window

test.html
test.js
another.js
Avatar of Gary
Gary
Flag of Ireland image

Because by the time your code has run the js file is still loading - js doesn't wait for external events, it carries on running.
Simple solution is to add a call in the dynamic js to call the testExternalSource function and not in the parent page or add a callback in your function to run when it is loaded.
You should assign the script an id and launch getElementById("myScript").src="myFile.js"; I guess.
Avatar of anAppBuilder

ASKER

Thank you both.

Gary, can you explain what you mean by "add a call in the dynamic js to call the testExternalSource function and not in the parent page "?  

I understand the callback approach, but would prefer not to have all added code be running in callbacks.

Sar1973 I tried adding this line to test.html
<script id = "ext" type="text/javascript" src=""></script>

Open in new window

and changing function addJavaScript() to
document.getElementById("ext").src ="another.js";

Open in new window

but that does not work.
In your master page you have
function testAnotherJs() {
	addJavaScript();
	testExternalSource();
}

Open in new window

Remove testExternalSource(); and put it in your dynamic js file
testExternalSource();
function getExternalString() {
	var extString = "A string from another.js";
	return extString;
}

Open in new window


The other way is to attach a callback to the script load
http://www.nczonline.net/blog/2009/07/28/the-best-way-to-load-external-javascript/
It still means you cannot run your testAnotherJs function as it is
Thank you again, Gary.  I moved my testExternalSource function to the second .js and that does not solve the problem.

My code is attached.
test.html
test.js
another.js
ASKER CERTIFIED SOLUTION
Avatar of Gary
Gary
Flag of Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Beautiful...Thank you!