Search code examples
javascripthtmlincludealertscript-tag

JavaScript function stops working when it is moved to an external .js file


I moved a function from an html page to an included reference file. It stopped working.

The complete contents of the file are:

alert('file included');

function doAlert() {
   alert('functions work');
}

In the html page, I have

<html>
<head><title>Page</title></head>
<body>
  HTML Template Header

  Some Content 

  ASP.NET MVC Partial View Starts
  <script type="text/javascript">
      doAlert();
  </script>
  ASP.NET MVC Partial View ends

  HTML Template Footer

  <script type="text/javascript" src="/Scripts/wtf.js"></script>
</body>
</html>

The 'file included' alert works, but the 'functions work' does not. What am I doing wrong?


Solution

  • Make sure you include the file before you execute the function.

    <script src="file.js" type="text/javascript"></script>
    <script type="text/javascript">
       doAlert();
    </script>