Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call javascript function from <script> tag?

Tags:

<html>  <script>     //some largeFunction()      //load a script dynamically based on the previous code     document.write("<script src='//...'><\/script>");  </script> </html> 

Question: is it possible to move the largeFunction() out of the static html page and put it into a js file? If yes, how could I then call that function statically before writing the <script> tag?

like image 376
membersound Avatar asked Feb 24 '16 15:02

membersound


People also ask

How do you call a function in script tag?

Calling a function using external JavaScript file Js) extension. Once the JavaScript file is created, we need to create a simple HTML document. To include our JavaScript file in the HTML document, we have to use the script tag <script type = "text/javascript" src = "function.

How do you call a JavaScript function from HTML?

Step 1: Firstly, we have to type the script tag between the starting and closing of <head> tag just after the title tag. And then, type the JavaScript function. Step 2: After then, we have to call the javaScript function in the Html code for displaying the information or data on the web page.

How do you call a function from an external js file 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.

Can we use script tag in JavaScript?

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.


1 Answers

Short answer: Yes.

As long as you load the first script containing the function first, you can call the function anywhere, as long as it's loaded first.

<script src="file1.js" type="text/javascript"></script>  <script src="file2.js" type="text/javascript"></script>  

In this example, make sure file1.js contains your largeFunction() function. You can then call largeFunction(); inside file2.js.

You can also do this:

<script src="file1.js" type="text/javascript"></script>  <script>     largeFunction(); </script> 

Just make sure your FIRST script contains the function.

like image 124
MortenMoulder Avatar answered Oct 05 '22 22:10

MortenMoulder