Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the danger in including the same JavaScript library twice?

One of the webapps I'm working in is made up of many partial HTML files. If the partial requires a JavaScript library such as YUI, the YUI library is included in the partial.

When the partials are combined at runtime, the resulting HTML often includes the YUI library several times.

<html>
... 
<script type="text/javascript" src="/js/yahoo/yahoo-min.js"></script>
... 
<script type="text/javascript" src="/js/yahoo/yahoo-min.js"></script>
... 
<script type="text/javascript" src="/js/yahoo/yahoo-min.js"></script>
...
</html>

I've seen strange behavior from including jQuery several times, especially when using AJAX. Why, specifically, is including the same JavaScript library more than once a bad idea? Why does it only sometimes cause problems?

like image 470
Eric the Red Avatar asked Feb 03 '11 20:02

Eric the Red


2 Answers

Depending on the library, including it more than once could have undesired effects.

Think of it like this, if you have a script that binds a click event to a button, and you include that script twice, those actions will be ran twice when the button is clicked.

You could write a simple function that you call to load a script and have it keep track of files that have already been loaded. Or, I'm sure you could probably use a pre-existing JS loader such as LabJS and modify it.

like image 189
simshaun Avatar answered Oct 18 '22 01:10

simshaun


You should take an approach I learned examining the source of HTML5 Boilerplate:

<script>
    !window.YAHOO && document.write(
        unescape('%3Cscript src="/js/yahoo/yahoo-min.js"%3E%3C/script%3E')
    );
</script>

I don't use YUI, so replace !window.YAHOO with whatever global YUI uses.

This approach will only load the library if it does not yet exist in the global scope.

like image 29
Stephen Avatar answered Oct 18 '22 02:10

Stephen