AJAX html 存根——加载清除的 head 元素是否实用?
我正在尝试实现一个“尽可能简单”的解决方案来在后台加载页面。我几乎只想用来自 ajax 存根的元素替换 html 中的某些元素。我当然遇到了以下标准问题:
- JavaScript 依赖
- 项 样式依赖项
- 设置标题
我的 AJAX 存根相当简单 - 实际上,它是整个页面,放入未命名为 head 或 body 的标签中(jQuery/浏览器不喜欢解析这些节点)。例如:
<html-stub>
<head-stub>
<title>Page Title</title>
<script type="text/javascript" src="somescript"></script>
<link rel="stylesheet" type="text/css" href="somestylesheet">
</head-stub>
<article>Some Content to replace in the origin document</article>
</html-stub>
做这样的事情是否安全/实用/完全愚蠢:
var stub = $(ajaxHTML);
var head = $(document).find('head');
// empty the current head -- later on we'll just empty things like title
head.empty();
// add all the crap
stub.find('stub-head').children().appendTo(head);
或者这只是一个非常糟糕的主意?我已经在现代浏览器中进行了测试,似乎工作正常,旧浏览器中是否也存在陷阱?
I'm trying to implement a "as-simple-as-possible" solution for loading pages in the background. I pretty much just want to replace certain elements within my html, with ones coming from the ajax stub. I've of course run into the standard problems of:
- JavaScript Dependencies
- Styling Dependencies
- Setting Title
My AJAX stub is fairly simple -- actually, it's the entire page, put into tags not named head or body (jQuery/browser doesn't like parsing these nodes). For instance:
<html-stub>
<head-stub>
<title>Page Title</title>
<script type="text/javascript" src="somescript"></script>
<link rel="stylesheet" type="text/css" href="somestylesheet">
</head-stub>
<article>Some Content to replace in the origin document</article>
</html-stub>
Is it safe/practical/completely stupid to do something like:
var stub = $(ajaxHTML);
var head = $(document).find('head');
// empty the current head -- later on we'll just empty things like title
head.empty();
// add all the crap
stub.find('stub-head').children().appendTo(head);
Or this is just a really bad idea? I've tested in modern browsers and it seems to work ok, are there also pitfalls in older browsers?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不认为你所做的有什么问题。您可以使用 JS 或 jquery 模板来更简单地做到这一点。另外假设您已经通过这种方法考虑了 SEO 和可访问性。
I don't see a problem with what you're doing. You could potentially do it simpler with JS or jquery templating. Also assuming you've taken into account SEO and accessibility with this approach.
动态内容通常以 xml 或 json 等格式发送。你的存根确实是 xml。然后设置所需节点的innerhtml 属性。这与你正在做的事情非常相似。尝试为您的节点提供 id 属性。然后您可以更轻松地访问它们。你可以这样说:
或者
The dynamic content is usually sent in a format like xml or json. Your stub is really xml. Then you set the innerhtml property of the desired node. It is pretty similar to what you are doing. Try giving your nodes id properties. Then you can access them more easily. You can say something like:
or