简体   繁体   English

在页面加载之前调用javascript函数

[英]Call javascript function before page loads

I'm calling a function load() on body's onload event. 我在主体的onload事件上调用函数load()。 Sometimes this function work and sometime it doesn't. 有时,此功能有效,有时则无效。 As per my understanding, until the body is completely loaded, this function will not get called. 根据我的理解,在主体完全加载之前,不会调用此函数。 Is there any way I can call this function before the page get loaded ? 有什么办法可以在页面加载之前调用此函数?

Here is home.html: 这是home.html:

<script src="js/custom.js"></script>
<script src="js/props.json"></script>
<body onload="load()">

<a id="beginner">Beginner Level</a>
        <div id="beginner-sub" class="well">
            <!-- append content here -->
        </div>

</body>

custom.js load function: custom.js加载函数:

function load() {
    var mydata = JSON.parse(beginner);  
    var rows = "";
    for(var x=0; x < mydata.length; x++)
    {
    rows += '<a href="'+mydata[x].url+'">'+mydata[x].title+'<i class="fa fa-hand-o-right pull-left" aria-hidden="true"></i></a><hr>';
    }
    $("#beginner-sub").append(rows);
    $("#beginner-sub hr:last-child").remove()
}

And this is my props.js 这是我的props.js

beginner = '[{"title" : "Simple Program", "url" : "simple.html"}, {"title" : "Check Palindrome", "url" : "palindrome.html"}]';

If you move the code inside the script tag it is executed immediately when found: 如果将代码移到脚本标签内,则在找到后立即执行:

<head>
...
<script type="text/javascript">
     alert("executed now"); 
</script>
</head>

This is for answering to your question about executing code before page loads. 这是为了回答有关在页面加载之前执行代码的问题。 But if you access some element, you have to ensure that this code is executed after the element has been loaded. 但是,如果访问某个元素,则必须确保在加载该元素后执行此代码。

ps you could also split up your code, parsing the JSON before the page loads, saving results inside a variable, and then append elements after the page has been loaded. ps您还可以拆分代码,在页面加载之前解析JSON,将结果保存在变量中,然后在页面加载之后追加元素。

No, can't (or shouldn't) force the body onload event to fire, but you can add a script tag immediately after the element in question. 不可以,不能(或不应该)强制触发body onload事件,但是您可以在有问题的元素之后立即添加脚本标签。

<a id="beginner">Beginner Level</a>
<div id="beginner-sub" class="well">
     <!-- append content here -->
</div>
<script>load();</script>

Do note though, that any other functions the load() depends on must have been loaded or else it will fail 不过要注意, load()依赖的任何其他函数必须已经加载,否则它将失败

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

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