[英]handle external javascript script loaded event before it's executed
I have an html
page and a script
which I want to handle in specific way: after it's loaded but before it's executed. 我有一个
html
页面和一个script
,希望以特定的方式处理:加载后但执行之前。 Basically I want to pre-load script but execute when certain criteria met. 基本上,我想预加载脚本,但是在满足某些条件时执行。 Script doesn't depend on other scripts so I make it non-blocking (
async
): 脚本不依赖于其他脚本,因此我将其
async
非阻塞( async
):
<script onload='onScripLoad()' scr='...' async></script>
All I want is something similar to onload
but which is executed before the downloaded script. 我想要的只是类似于
onload
但在下载脚本之前执行。 Is it possible? 可能吗?
The issue here is that I'm able to pre-load the script but unable to sync with the required event in my app lifecycle. 这里的问题是,我能够预加载脚本,但无法与应用程序生命周期中的必需事件同步。 The
onScripLoad
is executed after
script has been loaded AND
after
it has been executed. onScripLoad
after
脚本加载after
AND
执行after
执行。 What I need is to have control when script is executed (postpone execution). 我需要的是在执行脚本(推迟执行)时进行控制。
Adding more details I want to pre-load the script and execute it when certain element is available in the body
but I cannot put the script right after that element because in this case it gets queued with a few other resources which are being downloaded in the head
. 添加更多详细信息,我想预加载脚本并在
body
某些元素可用时执行该脚本,但是我无法将该脚本放在该元素之后,因为在这种情况下,该脚本与正在下载的其他一些资源排队head
。 Thus I want to place my script in the head
, make it async
and once it's downloaded execute only when specific element is available (or event create that element before executing). 因此,我想将我的脚本放在
head
,使其async
,并在下载后仅在特定元素可用时执行(或在执行之前创建该元素)。 I cannot make it not async because it's a script which I have no control and wouldn't like my whole page depend on it. 我不能使它不异步,因为它是我无法控制的脚本,也不希望我的整个页面都依赖它。
You could just load the external script in the head section, wrap the logic inside a function, and then call that function inside a condition at a later point: 您可以只在开头部分加载外部脚本,将逻辑包装在函数中,然后在稍后的条件中调用该函数:
externalscript.js: externalscript.js:
function externalFunction(data) {
console.log(data);
}
Index: 指数:
<head>
<script src='externalscript.js' async></script>
</head>
<body>
<script>
var body_data = 'test';
if (timing-driven-condition) {
externalFunction(body_data);
}
</script>
</body>
The function externalFunction
would be loaded first, but wouldn't be used until it was called within the condition, giving you control over when it executes. 函数
externalFunction
将首先被加载,但是直到在条件内被调用时才使用,从而使您可以控制何时执行。
Hope this helps! 希望这可以帮助! :)
:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.