mikezang
mikezang

Reputation: 2489

JavaScript function can't be run in external file

I have two functions in external file, then I call A and B in HEAD script, and A can be run and B can't, but if I put B into head script, B also can be run. I am not sure why, what can I do?

HTML:

<head>
<script language="JavaScript" type="text/JavaScript">
<!--
function B(id) {
    var selected = document.getElementById(id)
    var arr = selected.options[selected.selectedIndex].text.split(" ");
    var value = ""
    for (var i = 1; i < arr.length; i++) {
        if (value != "") value = value + " ";
        value = value + arr[i];
    }
    return value;
}

function save() {
    A("msg");
    var x = B(id);
}
-->
...
<script type="text/JavaScript" src="js/my.js"></script>
</body>
...

my.js:

function A(msg) {
    scroll(0,0);
    var outerPane = document.getElementById('FreezePane');
    var innerPane = document.getElementById('InnerFreezePane');
    if (outerPane) outerPane.className = 'FreezePaneOn';
    if (innerPane) innerPane.innerHTML = msg;
}

function B(id) {
    var selected = document.getElementById(id)
    var arr = selected.options[selected.selectedIndex].text.split(" ");
    var value = ""
    for (var i = 1; i < arr.length; i++) {
        if (value != "") value = value + " ";
        value = value + arr[i];
    }
    return value;
}

Upvotes: 0

Views: 52

Answers (2)

Charlie Martin
Charlie Martin

Reputation: 8406

The safest thing to do is wrap the code in the head in a window.onload handler like this...

<head>
  <script type="text/javascript">
    window.onload = function(){
      // your external files are guaranteed to be loaded now
      // you can call A or B
    }
  </script>
</head>

onload is only fired after all external scripts have been loaded.

Here is a full example...

index.html

<!DOCTYPE html>
<html>
<head>
<title>Hello world</title>
<script>
function save() {
  A()
  B()
}

window.onload = function() {
  save()
}
</script>
</head>

<body>
The content of the document......
<script src="./external.js"></script>
</body>

</html>

external.js

function A() {
  alert('A ran')
}

function B() {
  alert('B ran')
}

NOTE: This is better than moving the external script to the head, like the other answers suggest, because external resources loaded in the head block the entire page render until they are loaded.

By leaving the external script at the end of the body tag, the page load will seem faster as the css/html will display immediately. Even if the javascript isn't loaded yet.

Upvotes: 2

Tran Ho
Tran Ho

Reputation: 1500

Add your external file before the script tag contains your "save" function.

<script language="JavaScript" src = "yourfile.js" type="text/JavaScript">
</script>
<script language="JavaScript" type="text/JavaScript">
   function save(){
           A();
           B();
   }
</script>

Upvotes: 0

Related Questions