I think this is a simple question. Imagine you have a page that initializes a JS variable named channel
:
<html>
<script>
$(document).ready(function() {
...
var channel = new Channel();
channel.send("helo");
}
</script>
<body>
<div id="placeholder"></content>
</body>
</html>
The page also contains a div with id="placeholder" which content is loaded using AJAX. That external content have to access the channel
variable.
Is there any good practice or advice about where to store the variable? The following code works but I do not like it:
<html>
<script>
var channel;
$(document).ready(function() {
...
channel = new Channel();
channel.send("helo");
}
</script>
...
</html>
Thank you.
No, in this case there is no other way as the global scope is the only scope both scripts share (edit: well, I guess this depends on how you actually add the content. How do you do it?)
The only thing you can do is to minimize the number global variables by using an object as namespace:
You could put the loading AJAX function inside of the anonymous function that is executed when the DOM has loaded along with the channel variable. Both will then be scoped only to the anonymous function and scopes therein.