What is the outcome in javascript with multiple librarys that use $
Asked Answered
H

3

10

Let's pretend this is in the <head> of your html page.

OOPS this was a bit that was missing before...:

<script type="text/javascript" src="/include/js/billys.js"></script>
<script type="text/javascript" src="/include/js/susies.js"></script>
<script type="text/javascript" src="/include/js/marys.js"></script>

Order of the 3 scripts could vary. What would be the outcome?

Billy defines $ as

function $ () {
 return false;
}

Susie defines $ as

function $ () {
 return document.getElementById('body');
}

Mary defines $ as

function $ () {
 alert('I wrote this');
}
Heliopolis answered 11/5, 2011 at 19:40 Comment(2)
Sorry, see the question now. I'm talking with external js files. Just to be clear.Heliopolis
as i said in my answer. whatever is last, is the definition of $Flatt
F
18

Whatever is last is the final definition of $

That is why in (for example) jQuery there is noConflict() which lets you use a different variable than $ for jQuery

Flatt answered 11/5, 2011 at 19:42 Comment(3)
So it is ALWAYS [ALWAYS], top down, and whatever is last is what it will use?Heliopolis
I'm confirming that you are saying the order of the scripts is really all that matters.Heliopolis
not unless you have a setTimeout(function(){window.$=undefined;},100); or window.onload defining the function :PRecrudesce
I
16

Why not try it?

function $ () {
 return false;
}
function $ () {
 return document.getElementById('body');
}
function $ () {
 alert('I wrote this');
}
$(); // alerts "I wrote this"

The later definition overwrites the existing one. This is why it's generally good practice to check whether a function already exists before defining it. e.g.

if (typeof $ !== 'function') {
    function $(){ /* your code */}
}

or to fail in some sensible way.

Ivied answered 11/5, 2011 at 19:44 Comment(5)
If the function exists, overwrite it with a blank function? I think you need to change your last example a bit.Erethism
@minitech Um, yeah, !== is what I meant. Comment added for clarity.Ivied
@Joel Good stuff- added to the answer.Ivied
I didn't use Jsfiddle since my question had to do with multiple external js files. I had accidentally posted the question with that bit missing at first..Heliopolis
@Doug Well, it's all the same thing. Multiple script tags are parsed sequentially, whether they're inline or external, and they are effectively one file.Ivied
E
5

The last function with the same name wins.

Erethism answered 11/5, 2011 at 19:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.