简体   繁体   中英

Placing 2 copies of javascript on same page

I have implemented some functionality using about 500 hundred lines of Javascript and some html and css. I would like to place 2 instances of this on the same page. This leads to a namespace conflict.

I can think of a tedious way of avoiding this: * As html elements are programatically accessed by IDs in Javascript, I would need to give them different ids. I'd need 2 versions of javascript functions that reference these ids. * I'd need separate versions of javascript state variables.

Is there a simpler way of doing this that doesn't require so much code duplication, but with different names? Is there any way to make each copy behave like a separate document in this sense ie in separate namespaces?

Thanks

Yes: Have the outermost function of your code accept the id (or other selector) that it operates on, then just call it twice.

Eg,

function doSomethingNifty(id) {
    // Your code doing nifty things with `id`
}

Call it:

doSomethingNifty("foo");
doSomethingNifty("bar");

Any functions you define within doSomethingNifty close over the id argument, and so they have access to the id related to the call to doSomethingNifty that they relate to.

Here's a complete, but very simple, example. The great thing is that this scales up easily. The pattern doesn't change, you just put more inside doSomethingNifty .

Live Copy | Live Source

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Simple Closure Example</title>
</head>
<body>
  <div id="foo">I'm foo, click me</div>
  <div id="bar">I'm bar, click me</div>
  <script>
    function doSomethingNifty(id) {
      document.getElementById(id).onclick = showMyInfo;

      function showMyInfo() {
        alert("id = " + id + ", text = " + this.innerHTML);
      }
    }

    doSomethingNifty("foo");
    doSomethingNifty("bar");
  </script>
</body>
</html>

Without going into too much detail about what you're trying to do, Refactoring it might help.

For example, Instead of having a locked down un-portable piece of code, Why not simply write the HTML first and then write the JS in a way that does the work needed.

Some things just don't scale well(for example, what happens if you wanted 4 instances on the same page?

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