1

I have an external javascript file called test.js as seen below. This file needs user configuration parameters passed to it, in this case user and show values.

<script type="text/javascript">
<!--//
  user = '123';
  show = 'appts';
//-->
</script>
<script src="{{ STATIC_URL }}js/widgets/test.js" type="text/javascript"></script>

Above is currently how I tell 3rd parties to add the script to their own site. However, I cannot help to feel this is a bad way to pass these values i.e. clashes.

Is the way I have done it acceptable? Is there a better way?

Prometheus
  • 32,405
  • 54
  • 166
  • 302

3 Answers3

2

A simple answer would be to append something to your variable names, such as:

<script type="text/javascript">
<!--//
  widget_test_12331_user = '123';
  widget_test_12331_show = 'appts';
//-->
</script>
Grim...
  • 16,518
  • 7
  • 45
  • 61
2

You can stick to namespace convention "reverted domain":

<script type="text/javascript">
<!--//
if (!org) var org = {};
if (!org.mylibrary_domain) org.mylibrary_domain = {};
if (!org.mylibrary_domain.settings) org.mylibrary_domain.settings = {};
org.mylibrary_domain.settings.user = '123';
org.mylibrary_domain.settings.show = 'appts';
//-->
</script>
<script src="{{ STATIC_URL }}js/widgets/test.js" type="text/javascript"></script>
ElmoVanKielmo
  • 10,907
  • 2
  • 32
  • 46
2

You can use the concept of javascript namespace (How do I declare a namespace in JavaScript?).

so you can add another js file named testConfig.js, which include :

var yourAppNamespaceTestConfig = {
    user: function(){ return '123' ;} ,
    show: function(){ return 'appts';}
};

then inside test.js, you can read the config by:

var user = yourAppNamespaceTestConfig.user();
var show = yourAppNamespaceTestConfig.show();

And if you're more about OO, try Coffeescript (http://coffeescript.org/). They introduce OO to your javascript.

Community
  • 1
  • 1
Dio Phung
  • 5,944
  • 5
  • 37
  • 55