mcbeav
mcbeav

Reputation: 12275

Why would javascript work embedded in html page, but not in external script?

I am using a simple script, and when the script is embedded into the actual html page it works just fine, but when it is thrown into an external .js the script no longer works, i am not seeing any errors in the console, it is a jquery delegate function, and i know that the external script is working, because there are other scripts in it that are currently working just fine.

just wondering if there is a cause to this problem, or if anyone else has encountered this.

Upvotes: 1

Views: 1154

Answers (1)

Jacob
Jacob

Reputation: 78920

If you're embedding the script in the body of the HTML document, and if your script relies on the existance of elements before the script in the body, then that same script wouldn't work if loaded as an external resource since that code would be executed before the HTML DOM is built.

To make sure your scripts work in either case, wrap any startup code in a $(document).ready(...) method.

Upvotes: 4

Related Questions