javascript function conflict or css select conflict

95 views Asked by At

I have a team of people working on a webpage which has lots of javascript libraries included in it and lots of classes . It's quite possible that one or two of these libraries or our developer's codes have functions with similar names or with the css to have the same selectors and classes. like this :

Javascript :

<script src="/src1"> ....  function func1() {} ......</script>
              .
              .
              .
<script src="/src2"> ........ function func1() {} ...</script>

Or css :

.content {... background-color:#fff; ...}

and another .content{... background-color:red; ...}

I have actually found some solutions for css but I was wondering is there any way or javascript or php library that I could use to parse javascript files to change javascript functions and calls names to a unique name?

2

There are 2 answers

0
m4lt3 On

For css a wrapper class (on a higher dom level) or a prefixed-class-name (eg. .my-content and .your-content) would do the job.

A wrapper class can be easily achived with sass or less. you do not need to change your existing code, you can just wrap it. But on the downside, you will not be able to use two .content classes at the time, since you need the wrapper class.

For js there are many solutions. Depending on your project they are more or less usefull. You could wrap some of your js as a jQuery Plugins or npm modules, to name only a few.

But I guess would need a simpler solution.

Namespacing your js code is the easiest way.

var yourFirstNamespace = {

    foo: func1() {
    },

    bar: func2() {
    }
};

var yourSecondNamespace = {

    foo: func1() {
    },

    bar: func2() {
    }
};

...

yourFirstNamespace.func1();
yourSecondNamespace.func1();
0
Siddharth On

You can namespace your javascript files.

Suppose you have two javascript files named file1.js and file2.js.

In file1.js:

var file1 = {
   func1: function func1(){},//and other methods 
};

In file2.js:

var file2 = {
   func1: function func1(){},
};

Now you can call these methods using file1.func1() and file2.func1().

A far as multiple css files with same class. That would not work. Just change the class name or add another name to it like in file1.css

class="file1 abc"

In file 2 you can add

class="file2 abc"