如何从 <script> 标签调用 javascript 函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35606147/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 17:58:36  来源:igfitidea点击:

How to call javascript function from <script> tag?

javascripthtml

提问by membersound

<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 htmlpage and put it into a jsfile? If yes, how could I then call that function statically before writing the <script>tag?

问题:是否可以将largeFunction()静态html页面移出并放入js文件中?如果是,我怎么能在编写<script>标签之前静态调用该函数?

回答by MortenMoulder

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.jscontains your largeFunction()function. You can then call largeFunction();inside file2.js.

在本例中,确保file1.js包含您的largeFunction()函数。然后你可以调用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.

只需确保您的第一个脚本包含该函数。

回答by Rajesh

You can try following options:

您可以尝试以下选项:



LargeFunction.js

大型函数.js

function largeFunction(){
  // This is a global function and is a part of window object.
  // This can be called from anywhere once the file is loaded.
}

index.html

索引.html

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


IIFE

国际金融研究所

These are functions that are executed only once when the file is loaded. They are called the moment they are compiled.

这些函数仅在加载文件时执行一次。它们在编译时被调用。

function largeFunction(){

}

(function(){
  largeFunction();
})()


You can even try without IIFE

你甚至可以在没有 IIFE 的情况下尝试

function largeFunction(){

}
largeFunction();


window.onload / $(document).ready()

window.onload / $(document).ready()

This events are fired once all elements are rendered. If your JS is manipulating any elements like managing UI states or creating controls like datepickersor searchable dropdownsor adding options to select, these events are preferred.

一旦所有元素都被渲染,这个事件就会被触发。如果您的 JS 正在操作任何元素,例如管理 UI 状态或创建控件,如datepickerssearchable dropdownsadding options to select,则首选这些事件。

Note:Both events are not same. You can refer following postwindow.onload vs $(document).ready()

注意:两个事件不一样。您可以参考以下帖子window.onload vs $(document).ready()

// Pure JS
function largeFunction(){

}

window.onload = function(){
  largeFunction();
}


// jQuery
function largeFunction(){

}

$(document).ready(function(){
  largeFunction();
})


Note:Its not a good practice to have large function. You should also try to split function to multiple functions

注意:拥有大函数不是一个好习惯。您还应该尝试将功能拆分为多个功能

function getData(callback){
  var data = ...
  // Gets data from server
  data = cleanData(data);
  data = processData(data);

  if(callback) callback(data); // callback refers to renderUI function
}

function cleanData(data){
  // Clean if any field needs formatting
  return data;
}

function processData(data){
  // You can permute logic to parse data
  return data;
}

function renderUI(data){
  // Update DOM element with data
}


function largeFunction(){
  getData(renderUI);
}

回答by Brian Driscoll

Without going into details about javascript modules, etc, I'll just address the easiest way for you to move forward and leave you to optimize as you see fit. Let's say you put largeFunction()into a separate file called myScript.js, then your HTML page setup would be like this:

没有详细介绍 javascript 模块等,我将只介绍最简单的方法,让您继续前进,并让您根据自己的需要进行优化。假设您放入largeFunction()一个名为 myScript.js 的单独文件,那么您的 HTML 页面设置将如下所示:

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

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

As you can see, all you really need to do is make sure that you reference the external script file before your current script tag. From there, you can call largeFunction()as you would have if it were embedded in your HTML.

如您所见,您真正需要做的就是确保在当前脚本标记之前引用外部脚本文件。从那里,您可以largeFunction()像嵌入在 HTML 中一样调用。

回答by andre mcgruder

If you grab DOM elements and add event handlers in your JavaScript you don't have to put functions on the HTML page. You could just make the JS file and link to it using a script tag. It would probably be best to place the script tag at the bottom of the page to ensure that all of the DOM has loaded.

如果您获取 DOM 元素并在 JavaScript 中添加事件处理程序,您就不必在 HTML 页面上放置函数。您可以制作 JS 文件并使用脚本标签链接到它。最好将脚本标签放在页面底部以确保所有 DOM 都已加载。

Example:

例子:

var getDomJquery = $("#got-Some-dom").on( "click", function(){
    // do some cool JS DOM stuff here
});


var getDomPureJs = document.getElementById("got-Some-dom").on( "click", function(){
    // do some cool JS DOM stuff here
});

In your HTML near bottom of the page.

在页面底部附近的 HTML 中。

<script src="myJsFile.js"></script>