简体   繁体   English

加载刷新页面后执行Javascript代码

[英]Executing Javascript code after loading refreshed page

I have a Javascript file that is split into to two parts. 我有一个Javascript文件,分为两部分。 The first part of the code ends by refreshing the current page. 代码的第一部分以刷新当前页面结束。 I would like to try to get the second part of the code to execute as soon as the page reloads, but I am having trouble finding a way to implement this. 我想尝试在页面重新加载时立即执行代码的第二部分,但我无法找到实现此方法的方法。 I pretty much want a way to do 我非常想要一种方法

window.onload = someFunction() 

except that it activates the function after reloading the page due to the first part of the Javascript. 除了由于Javascript的第一部分而重新加载页面后它激活了该函数。 Is there an effective way to do this? 有没有有效的方法来做到这一点?

Use 使用

document.onload = somefunction() Instead . document.onload = somefunction()相反。 This will get executed immediately after the DOM loads . 这将在DOM加载后立即执行。

You can also use the jQuery to do the same like 你也可以使用jQuery来做同样的事情

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

You could do that using Jquery. 你可以使用Jquery做到这一点。 This is executed on page loading 这是在页面加载时执行的

$(function() {
    callMyFunction()
});

The only way I can think of is to add query string value when refreshing, then read that value and act upon it. 我能想到的唯一方法是在刷新时添加查询字符串值,然后读取该值并对其进行操作。

You can use such code: 你可以使用这样的代码:

function ParseQueryString() {
    var result = [];
    var strQS = window.location.href;
    var index = strQS.indexOf("?");
    if (index > 0) {
        var temp = strQS.split("?");
        var arrData = temp[1].split("&");
        for (var i = 0; i < arrData.length; i++) {
            temp = arrData[i].split("=");
            var key = temp[0];
            var value = temp.length > 0 ? temp[1] : "";
            result[key] = value;
        }
    }
    return result;
}

window.onload = function WindowLoad() {
    var QS = ParseQueryString();
    var reloaded = QS["reloaded"];
    if (reloaded === "1") {
        //execute second part of code
    }
}

Then when reloading, redirect to same page adding ?reloaded=1 otherwise (if this flag is already raised) don't refresh the page again to avoid infinite loop. 然后在重新加载时,重定向到同一页面添加?reloaded=1否则(如果已经引发此标志)不再刷新页面以避免无限循环。

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

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