2

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.

2
  • This approach works well for me: stackoverflow.com/questions/2866866/… Commented Feb 22, 2011 at 0:06
  • p.s. $(function() { instead of $(document).ready(function() { Commented Feb 22, 2011 at 0:08

2 Answers 2

1

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:

var your_namespace = {};
$(document).ready(function() {
   ...
   your_namespace.channel = new Channel();
   your_namespace.channel.send("helo");
}
Sign up to request clarification or add additional context in comments.

1 Comment

I do an $.ajax() call and I load the result with $("#placeholder").html(result)
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.