0

I have two div in my html file and I am using two external javascript files.but the problem is when I am using both the js file together I am not getting the required functionality.so I want to restrict the use of js file to particular div

e.g: div1 should only use js1 file and div2 should only use js2 file so that no clash happens and I get the required functionality.

I am making a web app which is using lot number of widgets and these widgets are getting loaded from the database.there is one admin panel where a admin can add widgets.i am fetching all the widget's code from the database in a same page.so in future it may happen that after adding lot many widgets and there related js files they clashes and create problme.so i want to restrict there use to certain widget

amit kumar
  • 29
  • 5

3 Answers3

1

Within a page (browsing context), there is only one JavaScript environment. To get the kind of isolation you're referring to, you'd have to create a separate browsing context by using an iframe or similar.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • I am making a web app which is using lot number of widgets and these widgets are getting loaded from the database.there is one admin panel where a admin can add widgets.i am fetching all the widget's code from the database in a same page.so in future it may happen that after adding lot many widgets and there related js files they clashes and create problme.so i want to restrict there use to certain widget – amit kumar Sep 01 '14 at 06:41
  • @amitkumar: To get that kind of isolation, you'd have to make them `iframe`s. – T.J. Crowder Sep 01 '14 at 06:58
0

no what you are saying isnt possible. but what instead you can do is use diff scope for diff javascripts.
If they are your own written js files
1. then simply change all the variables to be the properties of a global variables.
2. do not be dependent on the window variable
3. if your are using DOM manipulation using class names / tag names / attribute values which are common for both of the divs change them and also change the respective value on the div. So that you can access them sperately.

if they are one of the popular js libraries like jquery / _js / backbone use the default no conflict option provided to load separate versions and then use them separately on the two separate divs.

Parv Sharma
  • 12,581
  • 4
  • 48
  • 80
0

I am not sure if you are using jquery or plain javascript.

if it is jquery then you can use jquery noconflict. Create separate aliases to use jquery for div1 & div2

    <script>

        var div1Alias = $.noConflict();
        var div2Alias = div1Alias.noConflict();
        jQuery(document).ready(function(){
             alert(div1Alias( "#div1" ).html());
             alert(div2Alias( "#div2" ).html());
        });
    </script>

http://learn.jquery.com/using-jquery-core/avoid-conflicts-other-libraries/ How do I implement JQuery.noConflict() ?

Community
  • 1
  • 1
Avijit
  • 11