0

I am writing a third party javascript (my.js) that can be inserted in a HTML page using script tag. I want to achieve the following:

  • my.js gets loaded (which has a function myFunc(params))
  • myFunc() gets called with appropriate params (parameters can change)
  • putting my.js script in head is not an option

What is the best approach that I can use?

bhups
  • 12,839
  • 8
  • 45
  • 57
  • What's wrong with two script tags? Or call the function in `my.js`. *putting my.js script in head is not an option* how is this related to the problem? – Felix Kling Jun 14 '11 at 14:30
  • how is the site designer supposed to pass the parameters? – Alnitak Jun 14 '11 at 14:33
  • Your question doesnt make sense. What are you trying to do that you cant achieve with the link to file in the body? – Exitos Jun 14 '11 at 14:43
  • @Felix: two script tags are fine. But is there any way to achieve this functionality with just using a single script tag? – bhups Jun 17 '11 at 08:15

2 Answers2

1

The problem is that you can't really pass parameters w/ just 1 script tag pointing to an external file, so you would have to get them from some element in the DOM:

The html:

<html>
<body>
  <script src="my.js"></script>
  <input id="params" type="hidden" value="'param1', 'param2', 'param3'" />
  <div id="result"></div>
</body>
</html>

The javascript:

function myfunc() {
var doc = document,
 params = doc.getElementById("params").value.split(","); // make an array of params

doc.getElementById("result").innerHTML = params.toString();
}
window.onload = myfunc;

Honestly though, this is a kludge. As mentioned before by Felix, you should probably just use 2 script tags -- One to get the external js file and one to call the function with the parameters you need.

m1.
  • 1,115
  • 8
  • 9
1

You can pass parameters in via the query string and parse them out dynamically.

For example, your script tag becomes: <script src="my.js?foo=bar"></script>

You can then get the value of the URL using:

var scripts = document.getElementsByTagName('script');
var url = scripts[ scripts.length - 1 ].getAttribute('src');

Because of the order JS is loaded by the browser, the last script on the page (while your script is executing during load) should always be your script.

Then you parse the query string. There are a bunch of questions on Stack Overflow dealing with that. Ex: Parse query string in JavaScript

Community
  • 1
  • 1
Andrew Curioso
  • 2,126
  • 13
  • 24