简体   繁体   English

页面加载5秒后加载javascript吗?

[英]Load javascript after 5 seconds after page has loaded?

I have tried the following: 我尝试了以下方法:

<body id="myBody" onload = "setTimeout('a()', 5000)" / >

Is this the correct method? 这是正确的方法吗? The reason why I want to do this is because I have my entire website animating in (such as fade ins) on page load. 之所以要这样做,是因为我让整个网站都在页面加载时设置动画(例如淡入)。 Having my javascript only makes the animation unsmooth. 使用我的JavaScript只会使动画不流畅。

Any feedback appreciated. 任何反馈表示赞赏。

This code will work. 此代码将起作用。 Just set your time in milliseconds and write your JS code on loadAfterTime function: 只需设置您的时间(以毫秒为单位),然后在loadAfterTime函数上编写JS代码即可:

<script>
 window.onload = function(){
   setTimeout(loadAfterTime, 5000)
};


function loadAfterTime() { 
// code you need to execute goes here. 
}
</script>
window.addEventListener("load", function () {
    animation();
    setTimeout(otherOperation, 5000);
}, false);

function animation() {}
function otherOperation() {}

maybe you can use code like this 也许你可以使用这样的代码

<body id="myBody" onload = "setTimeout(a, 5000)">
尝试这个

if you are using jQuery your animation has a callback that you can use to delay the firing of all other javascript events like so: 如果您使用的是jQuery,则动画中会有一个回调,您可以使用该回调来延迟所有其他javascript事件的触发,例如:

$( window ).on( 'load', function () {

    $( '.someElements' ).animate({

        // properties to animate
    }, 300, function () {

        initScripts();
    });
});

function initScripts () {
  // call all other functions here
}

The Browser is always load all of your script if any when you open the web page. 打开网页时,浏览器始终会加载所有脚本(如果有)。 So It depend on when you call your javascript functions. 因此,这取决于您何时调用javascript函数。 Try this: 尝试这个:

document.ready(function(){ 
 // your code
});
or
$(function(){
     // your code
});

both of them make sure that all of element on your page have been loaded. 他们两个都确保页面上的所有元素均已加载。

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

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