gpt4 book ai didi

javascript - 避免对 HTML DOM 的所有内容进行 GET

转载 作者:行者123 更新时间:2023-11-28 09:28:14 25 4
gpt4 key购买 nike

上下文

我有一个 HTML5+CSS+JS 幻灯片,旨在通过一台无线路由器在国内 LAN 中的 50 个客户端之间同步。

问题

由于幻灯片的内容(主要是图片)可能太重,我想为每张幻灯片动态加载它们(例如,当客户端单击“下一页”按钮时),因为当前网站 GETs all 在页面加载时从服务器开始获取每张幻灯片的文件,从而使路由器重载。

this question (解决同一问题的另一种方法)用户建议我使用 AJAX 来仅获取 DOM,然后动态加载其内容。然而,他的解决方案对我不起作用,因为内容在我想要的那一刻之前加载了。

这种基于 AJAX 的方法正确吗?如果是这样,我可能做错了什么?

我的代码

slideshow.html(幻灯片结构)

<html>
<head>
<title>My Slideshow</title>
<script src="javascripts/slidesplayer.js"></script>
<link rel="stylesheet" href="/stylesheets/style.css">
</head>

<body>
<div id="slides-containter">

<div class="slide" id="slide_1">
<!--Contents such as images, text, video and audio sources -->
</div>

<div class="slide" id="slide_2">
<!--Contents -->
</div>

<!--A bunch of slides here-->

</div>
<script>
// Here I load the slides calling a function defined in slidesplayer.js
</script>
</body>
</html>

slideshow-placeholder.html(当我输入幻灯片 URL 时加载)

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="/path/to/ajaxSlidesScript.js"></script>
</head>
<body>
<h1>Hello slides!</h1>
</body>
</html>

ajaxSlidesScript.js

$(document).ready(function() {
$.ajax('/path/to/slideshow.html', {
async : false,
complete : function ajaxCallback(slidesDOM) {

// Pull out the individual slides from the slideshow HTML
$slides = $(slidesDOM.responseText).find('.slide');

// For each one ...
$slides.each(function prepareSlide() {

// Store a reference to the slide's contents
var $slideContent = $($(this).html()); // <--- GETs all the files for this slide which I want to avoid.

// Empty the contents and keep only the slide element itself
var $slideWrapper = $(this).empty();

// Attach to focus event handled by the slideware
$slideWrapper.appendTo('body').on('focus', function injectContent() {
// Put the content in — NOW external resources should be downloaded via GET and loaded, not before.
$slideWrapper.append($slideContent);
});
});
}
});
});

更新:这种方法不起作用,因为即使您没有将资源插入 DOM 中,操作 DOM 对象也会导致资源下载。你可以看看我在this question中做了什么.

最佳答案

Ajax 确实是解决您的问题的正确技术,但据我所知,您的问题很简单。

<script src="javascripts/slidesplayer.js"></script>
<link rel="stylesheet" href="/stylesheets/style.css">

对于这段代码,是否使用 ajax 并不重要,因为您已经加载了 CSS 文件,并且该 CSS 文件中引用的所有图像都会在开头直接加载。此外,您应该异步加载所有文件。

您可以添加<img>通过 JavaScript 标记并异步加载图像...

关于javascript - 避免对 HTML DOM 的所有内容进行 GET,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14042634/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com