anAppBuilder
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.
test.js
another.js
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>
test.htmltest.js
another.js
You should assign the script an id and launch getElementById("myScript") .src="myFi le.js"; I guess.
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
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>
and changing function addJavaScript() to
document.getElementById("ext").src ="another.js";
but that does not work.
In your master page you have
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
function testAnotherJs() {
addJavaScript();
testExternalSource();
}
Remove testExternalSource(); and put it in your dynamic js filetestExternalSource();
function getExternalString() {
var extString = "A string from another.js";
return extString;
}
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
ASKER
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
My code is attached.
test.html
test.js
another.js
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Beautiful...Thank you!
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.