jQuery in two external java script files -


i have html page 2 external javascript files

one global

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

and 1 local

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

obviously, use jquery

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

so far, good.

in both external javascript files, insert jquery code inside following piece of code

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

i've tried removing piece of code in local external javascript file since i've have on global file. doesn't work. so, question absolutely need start both external java script files piece of code? how make have on global file?

thanks

if have 2 javascript files, , you're doing dom manipulation in both files (using jquery) - yes, need start both $(document).ready(function(){...});.

here's what's happening....

|- browser requests page 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 running code before dom has been loaded... you're gonna run problems. likewise local.js.

you want run js (hooking dom events, etc) once page loaded.

if want have $(document).ready(function(){...}); in 1 of js files, can either:

  • hook own event (you'll have exact same problem though - pointless)
  • include js files @ bottom of page, after dom loaded.

personally, use document.ready() instead of placing scripts @ bottom of page.


Comments

Popular posts from this blog

php - Invalid Cofiguration - yii\base\InvalidConfigException - Yii2 -

How to show in django cms breadcrumbs full path? -

ruby on rails - npm error: tunneling socket could not be established, cause=connect ETIMEDOUT -