[英]Make sure JS file is loaded and JS function is called BEFORE calling another function
I have an issue with a tracking code that doesn't work properly since its called before a required JS script and function is loaded. 我有一个跟踪代码无法正常运行的问题,因为在加载所需的JS脚本和函数之前调用了该跟踪代码。 Here is the situation: 情况如下:
Upon successful form submission (CF7 on WordPress) the following function is called right away. 成功提交表单(WordPress上为CF7)后,立即调用以下功能。
function fn111Rooms(){
var email_address = document.getElementsByName("your-email")[0].value;
fnTransaction('Room booked', 'userid=' + email_address);
location.replace('http://example.com/thank-you');
}
The problem is, however, that the following script + function needs to be called beforehand to make everything work 但是问题是,需要预先调用以下脚本+函数,以使所有功能正常运行
<script type="text/javascript" src="http://www.example.com/Tracking.js"></script>
<script>fnPageHit('4ddc12d4344');</script>
This bit is placed in the section of each page but is not called again upon form submission since the form submits via AJAX (I believe that's the issue). 此位放置在每个页面的部分中,但在表单提交时不会再次调用,因为该表单是通过AJAX提交的(我相信这就是问题所在)。
How can I include the script into the fn111Rooms and make sure everything is called correctly and in order. 如何将脚本包含到fn111Rooms中,并确保正确并按顺序调用所有内容。 Really sorry in case that's a stupid question but JS is still confusing me from time to time. 真抱歉,这是一个愚蠢的问题,但是JS仍然不时使我感到困惑。
EDIT: Would this work? 编辑:这项工作吗?
function fn111Rooms(){
// Loads the script
var fileref=document.createElement('script')
fileref.setAttribute("type","text/javascript")
fileref.setAttribute("src", "http://www.example.com/Tracking.js")
// Calls the required function
fnPageHit('4ddc12d4344');
// Does the rest
var email_address = document.getElementsByName("your-email")[0].value;
fnTransaction('Room booked', 'userid=' + email_address);
location.replace('http://example.com/thank-you');
}
And then just call the one function when submitting the form.. ? 然后只需在提交表单时调用一个函数即可。
You could take a look at jQuery.when() 您可以看一下jQuery.when()
Lets say you have a function you have to execute 假设您有一个必须执行的功能
function yourFirstFunction(){
$.post('/somewhere');
}
And a second right after first one finishes 在第一个结束后的第二个
function yourOtherFunction() {
//stuff
}
Then you can use the following construction 然后您可以使用以下构造
$.when( yourFirstFunction() ).then(function(data) {
yourOtherFunction()
})
ie when yourFirstFunction
is done (ajax request finished) yourSecondFunction
will be executed 例如,当您的yourFirstFunction
完成(ajax请求完成)后,您的yourSecondFunction
将被执行
One way to do is applying infinite loop with some interval and checking following condition 一种方法是应用具有一定间隔的无限循环并检查以下条件
fnPageHit && fnPageHit('4ddc12d4344'); fnPageHit && fnPageHit('4ddc12d4344');
so whenevr the ile gets loaded u will get function in other cases fnPageHit will be undefined hence it will not execute and will no cause error 因此,当evr加载时,在其他情况下,u将获得功能。fnPageHit将是未定义的,因此不会执行,也不会导致错误
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.