Home  >  Article  >  Web Front-end  >  公共js在页面底部加载的注意事项介绍_javascript技巧

公共js在页面底部加载的注意事项介绍_javascript技巧

WBOY
WBOYOriginal
2016-05-16 17:28:18878browse

JavaScript脚本文件都放在页面底部加载,可以有效地加快页面的加载速度。
但是,php控制器一般这样写:

复制代码 代码如下:

$this->load->view($HEADER);
$this->load->view($MENU);
$this->load->view($VIEW_SHOW, $data);
$this->load->view($FOOTER);

$FOOTER是个共用模版,用于加载js及css文件。
$VIEW_SHOW作为主模版,则可能要单独写些js代码,这些代码通常需要使用公共文件的资源的话,把js写到$FOOTER的后面就不方便了,jQuery的$(document).ready又用不了。这时候,用window.onload就可以了,如下:
复制代码 代码如下:

window.onload = function() {
(function($) {
function test() {alert(123);}
//或写些基于jQuery的绑定什么的
})(jQuery)
};

但如果你想从window.onload外调用里面的函数,比如你想在这个窗口的子iframe中调用parent.test()是不会有结果的。
这时,变通一下,把函数作全局变量就可以了。
复制代码 代码如下:

var test; // 全局作用域的声明
window.onload = function() {
(function($) {
test = function() {alert(123);};
//或写些基于jQuery的绑定什么的
})(jQuery)
};

只在需要时,才把私有的函数改成全局的,是更安全的做法。
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn