简体   繁体   中英

How to structure a JavaScript/HTML website for global variables?

I'm building a dynamic website that gives travel directions, but I'm new to JavaScript and I'm not sure of the best way to code it.

Currently, I'm loading different parts of the site (header, main, footer) by having separate HTML pages for each element, and then loading these pages into the main page. For example, on the main page I have:

<body onload="initialize()">
   <div id="header"></div>
   <div id="main"></div>
   <div id="footer"></div>
</body>

And in the imported JavaScript script I have:

function initialize() 
{
   $('#header').load('header.html');
   $('#main').load('main.html');
   $('#footer').load('footer.html');
}

The issue is that I want all three of these imported pages to have access to global variables and functions in a single JavaScript file where I will be storing route information, coordinates, etc. Specifically, I ran into problems where I was unable to call a function in my main JS script from the header.html page that had been loaded into the parent page.

What is the best way to do this? Any help is much appreciated!

You should have a single js file with all your client side code in and include that on the page with a <script> tag. Then employ $( document ).ready() to run your initialisation. You can also define global variables here and assign them so they can be accessed later.

In your JavaScript include will be something like this;

var $header, $main, $footer

function initialize() 
{
   $header.load('header.html');
   $main.load('main.html');
   $footer.load('footer.html');
}

$(document).ready(function() {
  $header = $('#header');
  $main = $('#main');
  $footer = $('#footer');

  initialize();
});

Be careful with the number of global variables you create though see; 11 JavaScript mistakes you're making .

have you tried putting it outside on the function to make it global ...

var <variable name>
function <function_name>{

<variable name>

}

in main page.

<script type="text/javascript">
    variable = <value>;   //variable used with var keyword is considered as global variable
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM