简体   繁体   English

在CMS中加载时启动JavaScript函数的正确方法是什么?

[英]What is the proper way to initiate a JavaScript function on load in a CMS?

I need to call a function on page load. 我需要在页面加载时调用一个函数。 Typically this would be handled with a body onload call, however I'm in a CMS that reuses the body tag on multiple pages. 通常,这可以通过body onload调用来处理,但是我在CMS中,可以在多个页面上重用body标签。 I only need the script to run on a single page. 我只需要脚本在单个页面上运行。 Is there a next-best-location to initiate an onload function? 是否有下一个最佳位置来启动onload功能?

Use the window.onload event : 使用window.onload事件

window.onload = function() {  
    // do stuff
};

If you have access to jQuery, you can use one of the .ready() syntaxes : 如果可以访问jQuery,则可以使用.ready()语法之一

$(document).ready(function() {
    // do stuff
});

OR: 要么:

$(function() {
    // do stuff
});

If you are using jQuery, you can add a load event on window: 如果使用的是jQuery,则可以在window上添加load事件:

$(window).on('load', function(){
   // do stuff here
})

You also have DOM ready with jQuery: 您还可以使用jQuery准备DOM:

$(function(){
   //stuff here 
});

You can instantiate it in a separate js file, so it will only be called when that file is loaded, not the CMS template. 您可以在单独的js文件中实例化它,因此仅在加载该文件时调用它,而不在CMS模板中调用它。 ie

window.onload = function(){
// Do stuff
};

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

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