简体   繁体   English

加载后如何立即在动态加载的javascript上执行功能?

[英]How to execute function on dynamically loaded javascript immediately after loading?

I am confused by the answer to this question: Execution of dynamically loaded JS files 我对以下问题的答案感到困惑: 动态加载的JS文件的执行

I have some html: 我有一些HTML:

<html>
    <head>
        <script type="text/javascript" src="/scripts/onload.js"></script>
    </head>
    <body onload="loadscript()">
    </body>
</html>

loadscript() inserts another script into the head. loadscript()将另一个脚本插入头部。 How do I immediately call a function from the inserted script ? 如何立即从插入的脚本中调用函数? (without using jQuery) (不使用jQuery)

EDIT: The script to be inserted is determined at run time depending on the path of the current page. 编辑:要插入的脚本是在运行时根据当前页面的路径确定的。

You can't immediately run code in your new script because the browser has to fetch it over the network first. 您无法立即在新脚本中运行代码,因为浏览器必须首先通过网络获取代码。 That takes time, so it's an asynchronous action - the code that inserted the script tag will continue to execute whilst the script is fetched in the background. 这需要时间,所以这是一个异步操作-插入脚本标签的代码将在后台获取脚本的同时继续执行。

Once the new script file has arrived the JavaScript engine will parse and execute it as soon as possible. 一旦新的脚本文件到达,JavaScript引擎将解析并尽快执行它。 If some other JavaScript code is already executing (an event handler, for example), it will wait for that code to finish before executing your new script. 如果其他一些JavaScript代码已经在执行(例如,事件处理程序),它将在执行新脚本之前等待该代码完成。 This article is a great explanation of the JavaScript asynchronous execution model. 本文很好地解释了JavaScript异步执行模型。

You can't control exactly when your new script is executed, but you can call a function from the top level of your new script to have it executed as soon as possible : 您无法精确控制执行新脚本的时间,但可以从新脚本的顶层调用一个函数以使其尽快执行:

function myFunction() {
  // code to execute when the second script is included
}

myFunction();

If you don't need to refer to this function anywhere else you can save some characters my using an IIFE : 如果您不需要在其他任何地方引用此功能,则可以使用IIFE保存一些字符:

!function() {
  // code to execute when the second script is included
}()

(or (function() { /* ... */ }()) , or any of the other variants on IIFE syntax). (或(function() { /* ... */ }()) ,或IIFE语法上的任何其他变体)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM