Ash*_*ani 13 html javascript jquery
我正在寻找一种在页面完全加载后加载jquery的方法.
这里有很多关于它的问题和答案,但都描述了如何在页面或jquery完全加载后运行需要jquery的脚本.
我正在寻找的是加载页面然后调用jquery并在加载jquery之后调用函数.就像是:
document.onload=function(){
var fileref=document.createElement('script');
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", 'http://code.jquery.com/jquery-1.7.2.min.js');
//Here I need an event to know that jquery is
//loaded to run stuff that needs jquery
}
Run Code Online (Sandbox Code Playgroud)
Mr.*_*tle 23
试试这个:
$(document).ready(function() {
// When the document is ready
// Do something
});
Run Code Online (Sandbox Code Playgroud)
您还可以使用:
$(window).bind("load", function() {
// Your code here.
});
Run Code Online (Sandbox Code Playgroud)
对于您的问题,解决方案可能是将谷歌托管的CDN附加到某个库:
https://developers.google.com/speed/libraries/devguide
此外,您可以在页面底部(之前</body>)添加:
<script type="text/javascript">
(function() {
var script = document.createElement('script')
script.setAttribute("type", "text/javascript")
script.setAttribute("src", "https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js")
document.getElementsByTagName("head")[0].appendChild(script)
})();
</script>
Run Code Online (Sandbox Code Playgroud)
但是,我认为这是冒险的.你有一个异步调用jquery,因此你的jquery必须等到它加载(即$(document).ready在这种情况下不起作用).所以我的答案是:使用像谷歌建议的CDN; 把你的javascript放在底部</body>; 并忽略分析器中的标志.
我六年多前就问过这个问题,我得到的答案都有一些缺陷。后来我自己制定了一个解决方案,从那以后我一直在使用。现在我再次遇到我自己的问题,并且看到有很多观点,我想分享它,因为我认为它可能对其他人有帮助。
这个问题主要发生在主从类型的页面(可以是旧的 .master 和 .aspx 页面)或(asp.net 中的布局和视图)或任何类似的情况可能在其他 Web 开发语言上,但是总是有一个主-涉及细节模式。
对于解决方案,我只需在页面开头添加一个数组:
<script>var after = [];</script>
Run Code Online (Sandbox Code Playgroud)
任何需要 jQuery 或任何其他脚本的函数都将在本节之后运行,而不是运行它,我只是将其推送到此数组:
after.push(function(){
// code that requires scripts that will load later,
//might be for example a jQuery selector or ...
});
Run Code Online (Sandbox Code Playgroud)
然后在页面的最后,在关闭 body 标签之前(当然现在已经加载了脚本),我运行(此处命名的)数组内的所有函数after:
<script>for(var i=0;i<after.length;i++)after[i]();</script>
</body>
Run Code Online (Sandbox Code Playgroud)
我发现这种方法非常容易、简单且完美。