The tcategories function is not available from the js file. What is the problem?

<html> <head> <script src="/all.js" type="text/javascript"></script> </head> <body> ... <script type="text/javascript"> function tcategories() { alert(1); } </script> </body> </html> 

all.js:

 setTimeout(function() {tcategories()}, 3000); 

Console:

Uncaught ReferenceError: tcategories is not defined

  • Very strange. I copied your code - everything worked as it should. Maybe the problem with the rights of files? - Pavel Sotnikov
  • You call a function in a file connected in the header, but the function itself is announced in the body of the document. Either move tcategories () to all.js, or connect all.js after announcing the function - dekameron

1 answer 1

Well, firstly there is no guarantee that the code from all.js is executed after the script is loaded from the DOM. Lead not on timeout, but on document.ready. Also in all.js, you can define var functions = {} and in the script assign the value functions.tcategories = function ()...;