'Imported js function throw a not defined error

I am getting this error validate_allocation is not defined when trying to execute a function from a static file. Any idea why?

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="static/main.js"></script>
<script>
validate_allocation();
</script>

main.js

$(function() {
    alert('test'); // I can see this, so the file is imported for sure
    function validate_allocation(){
        alert('test');
    }
}); 


Solution 1:[1]

The purpose of $(function() { ... }); is to run the code inside once the page has finished loading. As others have said, you're defining a function not only after the page has finished loading (and therefore after the call is made in your HTML file), but it is also limited to the scope of that block. It can safely be moved out of the block:

// Declare function at the root of the document and make it accessible to the HTML page
function validate_allocation(){
    alert('test');
}

// Actions to perform when the page has completed loading
$(function() {
    alert('test'); // I can see this, so the file is imported for sure
}); 

Solution 2:[2]

Remove the Validate_allocation function from jquery onload function. Since you are writing in that function it will be scoped to that function only.

function validate_allocation(){
        alert('test');
    }
$(function() {
    alert('test'); // I can see this, so the file is imported for sure    
}); 

This will make the function globally accessible

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Eraph
Solution 2 praveen