简体   繁体   English

如何引用将在脚本加载后声明的 function

[英]How to refer to a function that will be declared after script loading

In a Sitecore environment, where I CANNOT reorder the js scripts instantiated at the end of the <body> , I need to check if one of the function ( Gigya ) in those scripts has returned a true value ( I need to check if a user is logged in or not ).在 Sitecore 环境中,我无法重新排序在<body>末尾实例化的 js 脚本,我需要检查这些脚本中的 function ( Gigya )之一是否返回了真值(我需要检查用户是否是否登录)。

My script can be loaded ONLY before those scripts are loaded, so my script checks if a given function has a true return value before that said function has to be called.我的脚本只能在加载这些脚本之前加载,所以我的脚本在必须调用 function 之前检查给定的 function 是否具有真正的返回值。

Given the structure situation, what I always get is an error of unknown function.鉴于结构情况,我总是得到一个未知 function 的错误。

Is there a way to bypass this?有没有办法绕过这个? I mean, I have tried to attach at the body an ad-hoc script containing my check-function at the end of the loading process, but with no success.我的意思是,我试图在加载过程结束时在正文中附加一个包含我的检查功能的临时脚本,但没有成功。

Any hint?有什么提示吗? Maybe adding listeners?也许添加听众?

Approach 1方法一

Since the function you need to wait for is loaded with <script> tags you could wrap your entire code inside a function and call that function with onload由于您需要等待的 function 加载了<script>标签,您可以将整个代码包装在 function 中并调用 function

<script src="...gigya..." onload="functionToExecute()">

Approach 2方法二

instead of calling the functionToExecute you could create a new synthetic event, say "gigyaloaded" and listen to it before your functions are called.您可以创建一个新的合成事件,而不是调用functionToExecute ,例如“gigyaloaded”并在调用函数之前收听它。

[ https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events ] [ https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events ]

the event should be emitted with script onload like above.该事件应该与上面的脚本 onload 一起发出。

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

相关问题 JavaScript声明的函数在加载脚本时消耗多少内存? - How much memory does a JavaScript declared function consume on script loading? 加载外部脚本后运行函数 - Running a function after loading an external script 如何在 WinDbg 中引用不同脚本中定义的 JavaScript 函数? - How do I refer to a JavaScript function defined in a different script in WinDbg? JavaScript 提升:函数可以引用下面声明的另一个函数吗? - JavaScript Hoisting: Function Can Refer to Another Function Declared Below It? 如何在“脚本”数据类型AJAX请求之后访问声明的变量? - How to access declared variables after a “script” data type AJAX request? 如何引用 HTML 中的函数? - How to refer to a function in HTML? 加载页面后如何从内容脚本运行回调函数? 镀铬扩展 - How to run callback function from content script after loading page ? chrome extension javascript对象方法如何引用尚未声明的变量? - How can javascript object method refer to variable that is not declared yet? Javascript .setTimeout()如何引用一个函数 - Javascript .setTimeout() how to refer to a function 如何在Cloud Function中引用数组 - How to refer to an array in a Cloud Function
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM