Marco
Marco

Reputation: 2737

jQuery in two external java script files

I have an html page with 2 external javascript files

one that is global

<script src=".../js/global.js" type="text/javascript"></script>

and one that is local

<script src="js/local.js" type="text/javascript"></script>

Obviously, I use jQuery

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js" type="text/javascript"></script>

So far, so good.

In both external javascript files, I insert my jQuery code inside the following piece of code

$(document).ready(function() {
    // code goes here...
});

I've tried removing that piece of code in the local external javascript file since I've already have it on my global file. But it doesn't work. So, my question is do i absolutely need to start both external java script files with that piece of code? How do i make it so i only have it on my global file?

Thanks

Upvotes: 0

Views: 38

Answers (2)

Dave Salomon
Dave Salomon

Reputation: 3297

If you have 2 javascript files, and you're doing DOM manipulation in both files (using jQuery) - yes, you need to start both with $(document).ready(function(){...});.

Here's what's happening....

|- browser requests page from server
|
|- page has <script src="/scripts/global.js"></script>
|- browser requests /scripts/global.js
|- page has <script src="/scripts/local.js"></script>
|- server returns global.js
|- server returns local.js
|- page has (various other tags)
|- browser requests (various other tags)
|- 
|- page loaded - document.ready fires

So, if global.js is running code before the DOM has been loaded... you're gonna run into problems. Likewise with local.js.

You only want to run your JS (hooking up to DOM events, etc) once the page is loaded.

If you really want to only have $(document).ready(function(){...}); in one of your JS files, you can either:

  • Hook up your own event (you'll have the exact same problem though - this is pointless)
  • Include your JS files at the bottom of the page, after the DOM is loaded.

Personally, I always use document.ready() instead of placing scripts at the bottom of the page.

Upvotes: 1

Taplar
Taplar

Reputation: 24965

If your going to include your external scripts inside your <head> then it is most often a good idea to put them in document readies. If you are planning on including your scripts at the bottom of your <body> then they are unnecessary.

Upvotes: 2

Related Questions