I have two sets of <script>
tag blocks containing JavaScript functions and have put them in priority orders. One of the tags contain a src
to another external .js library file as shown below.
<script src='libtest.js'>
function helloworld() {
alert('hello world');
}
function callLibraryTest() {
runLibraryTest(); //Calls into libtest.js for auto test.
}
</script>
... some html ...
<script>
function callHello() {
helloworld();
}
</script>
The error I am getting is the callHello()
function does not have the helloworld()
defined. How do I solve that ?
Note that the scripts are deliberately separated because if they were bunched up, calling the callHello()
might end up not defined as well.
Thanks.
I have two sets of <script>
tag blocks containing JavaScript functions and have put them in priority orders. One of the tags contain a src
to another external .js library file as shown below.
<script src='libtest.js'>
function helloworld() {
alert('hello world');
}
function callLibraryTest() {
runLibraryTest(); //Calls into libtest.js for auto test.
}
</script>
... some html ...
<script>
function callHello() {
helloworld();
}
</script>
The error I am getting is the callHello()
function does not have the helloworld()
defined. How do I solve that ?
Note that the scripts are deliberately separated because if they were bunched up, calling the callHello()
might end up not defined as well.
Thanks.
Share Improve this question asked Aug 28, 2015 at 4:02 gsunnicgsunnic 3214 silver badges9 bronze badges 2-
developer.mozilla/en/docs/Web/HTML/Element/… - src:
This attribute specifies the URI of an external script; this can be used as an alternative to embedding a script directly within a document. script elements with an src attribute specified should not have a script embedded within its tags.
– Arun P Johny Commented Aug 28, 2015 at 4:04 -
I don't understand your remark about
callHello()
not ending up being defined. If you put it in a<script>
tag then it will be defined, whether it is in there with other functions or not. What made you concerned that they must be in separate script tags? – Dan Lowe Commented Aug 28, 2015 at 13:30
2 Answers
Reset to default 9If a <script>
tag has a src
attribute, it cannot also contain script text. Move the helloworld
function to a separate <script>
tag.
<script src="libtest.js"></script>
<script>
function helloworld() {
alert('hello world');
}
function callLibraryTest() {
runLibraryTest(); // Calls into libtest.js for auto test.
}
</script>
<!-- some html ... -->
<script>
function callHello() {
helloworld();
}
</script>
Assuming that you are trying to run "callHello" function when "libtest.js" is loaded successfully. As Dan already explained that a tag with src attribute cannot contain javascript code in its body. You can try a trick like callback method. For example modify the src tag to "libtest.js?callback=callHello" and at end of the libtest.js execute the callback method.
Hope this helps!