Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to refer to function or object from particular script tag in HTML file

Imagine we have the following code in an HTML file:

<script id='tag-1'>
  function foo(){
    alert("this is foo-1");
  }
</script>

<script id='tag-2'>
  function foo(){
    alert("this is foo-2");
  }
</script>

<script id='tag-3'>
  function foo(){
    alert("this is foo-3");
  }
</script>

Is it possible to invoke function foo from the script tag with id tag-2? I'm just curious to know if there is any cross-browser solution? Thank's guys.


Ok we have two very relevant proposals - the one that I marked for accepted answer and another one of the comments rigth below this post - the one that @dfsq propose. Thank you all guys!!!

like image 720
0xC0DEGURU Avatar asked May 31 '13 12:05

0xC0DEGURU


People also ask

How do you call a function from another script in HTML?

The first method is to call the JavaScript function in HTML. For this, you have to create a function then define this function either in the head section or body section of the HTML document. You can either create a link or a button and then an onclick() event is associated with them in order to call this function.

What is the function of script tag in HTML?

The <script> tag is used to embed a client-side script (JavaScript). The <script> element either contains scripting statements, or it points to an external script file through the src attribute. Common uses for JavaScript are image manipulation, form validation, and dynamic changes of content.

How do you call a script in HTML?

To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file. This script tag should be included between the <head> tags in your HTML document.


2 Answers

No, that's not possible without resorting to eval().

As each script block is evaluated by the browser the previous versions of the function are overwritten.

You can access the text context of each <script> tag, but only if it's inline. Accessing the source of <script src="..."> tags requires AJAX.

like image 75
Alnitak Avatar answered Sep 25 '22 01:09

Alnitak


Yes this is totally possible, but you should use a type other than text/javascript.

<script id='tag-1' type="myScriptHolder">
  function foo(){
    alert("this is foo-1");
  }
</script>

<script id='tag-2' type="myScriptHolder">
  function foo(){
    alert("this is foo-2");
  }
</script>

<script id='tag-3' type="myScriptHolder">
  function foo(){
    alert("this is foo-3");
  }
</script>

<script>
$.globalEval($('#tag-1').text();
</script>
like image 24
Serge Avatar answered Sep 22 '22 01:09

Serge