简体   繁体   English

jQuery加载功能页面加载问题

[英]JQuery load function page loading issue

I have a main.html in which I am trying to load another HTML. 我有一个main.html,我正在其中尝试加载另一个HTML。 The code in main.html is like this: main.html中的代码如下:

<script type="text/javascript">
$(window).load(function(){
    $("#divid").load("sample.html");
});
</script>

Inside the sample.html, I have another JavaScript which doesn't work as expected. 在sample.html内,我还有另一个JavaScript无法正常工作。

<!-- inside sample.html -->
<script type="text/javascript">
... Some JavaScript here ...
</script>

I do not even get the width of an element correctly. 我什至没有正确获得元素的宽度。 Surprisingly, if I put a breakpoint in the JavaScript or put an alert, all seem to work well. 出乎意料的是,如果我在JavaScript中添加了一个断点或发出了警报,那么一切似乎都可以正常工作。 This made me guess that page might not be loaded when script runs and by putting alert or breakpoint gives it a bit more time ? 这让我猜想脚本运行时可能无法加载页面,并且通过放置警报或断点使页面有更多时间? I did some searching on web and think that the loading is not in sync which means that the script inside the sample.html page is executing before the page could load. 我在网上进行了一些搜索,认为加载不同步,这意味着sample.html页面中的脚本在页面加载之前就已执行。 This is just my guess. 这只是我的猜测。 I have tried adding JQuery functions ready and load inside the sample.html as well but nothing changes. 我尝试添加JQuery函数准备就绪,并在sample.html中加载它,但是没有任何变化。 Any idea what could be wrong here ? 知道这里有什么问题吗?

Use the callback... 使用回调...

this is an example from the doku 这是来自doku的示例

    $( "#result" ).load( "ajax/test.html", function() {
  alert( "Load was performed." );
});

http://api.jquery.com/load/ http://api.jquery.com/load/

and also use jQuery's 并使用jQuery

$( document ).ready(function() {
    console.log( "ready!" );
});

Document ready fires the callback, when the dom is ready. 当dom准备就绪时,文档准备就绪会触发回调。 And load fires the callback when the file is loaded. 加载文件后,load会触发回调。

//EDIT Please use document ready... here are more details... and also do not load files directly from the file system //编辑请准备好文档...这里有更多详细信息...也不要直接从文件系统加载文件

$(document).ready(function(){
  // You will enter here, wenn the DOM is loaded and ready to use

  //When everything is ready to roll you want to  load your html file
   $("#divid").load("sample.html",function(){
     // You will enter this method when sample.html is loaded

     // Make sure there is also a div with the id=divid 
     // to get details on why this is not loading you can also use the
     // function signature  
     // $("#divid").load("sample.html",function(responseText, textStatus, jqXHR){});
     // You should also be aware of loading a file from file system can cause to ajax 
     // errors if it is not served by an http server. Because you can't access local
     // files from within JavaScript (security thing) 
   });


}

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

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