在页面加载之前调用javascript函数 [英] Call javascript function before page loads

查看:348
本文介绍了在页面加载之前调用javascript函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在body的onload事件上调用函数load().有时,此功能有效,有时则无效.根据我的理解,在主体完全加载之前,不会调用此函数.在页面加载之前,有什么方法可以调用此函数吗?

I'm calling a function load() on body's onload event. 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 ?

这里是 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 加载功能:

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()
}

这是我的 props.js

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

推荐答案

否,不能(或不应该)强制触发body onload事件,但是您可以在有问题的元素之后立即添加脚本标签

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.

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


不过请注意,load()依赖的所有其他功能必须已经加载,否则它将失败


Do note though, that any other functions the load() depends on must have been loaded or else it will fail

这篇关于在页面加载之前调用javascript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆