如何使用 jQuery 同步加载页面
目前,我正在使用 jQuery 来选择我的索引页应加载的内容,具体取决于是否设置了 cookie。
例如,如果设置了cookie,则index.html的body标签应加载hasCookie.html;如果未设置cookie,则应加载noCookieSet.html。
我的索引页当前有:
load user scripts
load styling scripts
<html><body></body></html>
用户脚本有检查 cookie 是否设置的代码。如果是,我使用 jQuery 的 load 将内容加载到正文中:
$(document.body).load('hasCookie.html')
但是,由于这是异步执行的,因此样式脚本在正文标记更新之前已加载,因此正文没有样式化。
有没有办法进行同步加载,或者我应该以错误的方式处理这个问题?
编辑:如果有帮助的话,样式脚本基本上是 jQueryUI
Currently I am using jQuery to choose what my index page should load depending whether a cookie is set.
For example, the body tag of the index.html should load hasCookie.html if the cookie is set and noCookieSet.html if no cookie is set.
My index page currently has:
load user scripts
load styling scripts
<html><body></body></html>
The user script has the code that checks whether the cookie is set. If it is, I use jQuery's load to load the content into the body:
$(document.body).load('hasCookie.html')
However, since this is executed asynchronously, the styling scripts have loaded before the body tag has been updated, hence the body is not styled.
Is there a way of having a synchronous load, or should am I approaching this in the wrong way?
EDIT: if it helps, the styling scripts are basically jQueryUI
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
AFAIK,JQuery 加载无法同步。
您可以使用回调函数来解决这个问题。
AFAIK, JQuery load cannot be synchronous.
You can cet around this witha callback function.
就您而言,这听起来像是如果可能的话,实现服务器端确实是一个更好的主意。在 PHP 中,检测 $_COOKIE 数组中是否设置了您想要的 cookie 并输出正确的页面是一件简单的事情。
In your case, this sounds like it would really be a better idea to implement server-side if possible. In PHP it would be a simple matter of detecting if the cookie you want is set in the $_COOKIE array and outputting the correct page.
您可以将其形成为 AJAX 请求并使用响应填充您的页面。将异步选项设置为 false。这个答案有更多: 如何让 jQuery 执行同步而不是异步 Ajax 请求?
You can form it as an AJAX request and populate your page with the response. Set the async option to false. This SO answer has more: How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?
只需将 document.location.href 更改为页面的 url 即可。
您正在做的是使用 ajax 加载内容并将其放置在页面主体中。如果您不希望请求 head 中声明的任何资源,您可以这样做。但这没有意义,因为你可以通过缓存来做到这一点。
Just change document.location.href to the url of the page.
What you're doing is loading content with ajax and placing it within the page body. You'd do this if you didn't want any resources declared in head to get requested. But there's no point in that since you can do it with caching.
尝试
此操作将推迟加载,直到其他所有内容都已存在之后。
Try
This will postpone loading until after everything else is already there.
我就是这样做的。
您可以在 Ajax 函数回调时附加样式和 Javascript。
这允许加载所有内容,包括样式和 javascript,前提是脚本名称和 css 文件名相同。
This is how i do it.
You can attach Style and Javascript upon callback from the Ajax Function.
This allows everything to be loaded including styles and javascript, given that the script name and css file name are the same.