简体   繁体   中英

Issue running function from external js file

I am trying to do something which I feel should be elementary and basic but it is not working. I have looked at many related Stackoverflow QAs but none covers this exact issue.

I want to run a function from an external js file called main.js. The file is loaded at the bottom of the body section of an html page in the usual way. All contents of the file is within the standard jQuery wrappers. I know it is loading properly because I can see it in Developer Tools and various animations coded in it are running correctly. I have jQuery 3.3.1 loaded in the head section of the page and again it must be loading properly because the animations are working.

As a test I have the following function in main.js:

function alerttest() {
  alert('Function test works');
}

Then in the main body of the html page I call the function as follows:

<script>
  alerttest();
</script>

So when I refresh the page I should get an alert but this does not happen. I get an error in the console: Uncaught ReferenceError: alerttest is not defined . This would happen if I loaded scripts in the wrong location so I also tried this to call the function so the DOM would be loaded first:

<script>
$(function() {
  alerttest();
});
</script>

but I get the same Reference error. Can anyone suggest what is going on?

Environment: Windows 10, VSCode, Codeigniter 3, jQuery 3.3.1, WAMP with PHP 7.4.7

I believe I have solved the problem and, as I suspected, it was about the location of scripts. I have always been advised to include scripts at the bottom of the page just above the closing body tag but this didn't work in this instance. I have now located my main.js in the head section along with the jQuery CDN and everything works just fine.

Many thanks for responding.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM