为了提高网站的性能,我更新了我的 javascript 引用以使用 defer,例如:
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous" defer></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.16.0/jquery.validate.min.js" defer></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validation.unobtrusive/3.2.6/jquery.validate.unobtrusive.min.js" defer></script>
<script src="js/plugins.js" defer></script>
<script src="js/main.js" defer></script>
这确实提高了页面加载性能。不幸的是,一个副作用是处理表单发布的 jquery 函数不再使用 AJAX 完成,它尝试重新加载整个页面,这导致仅返回的内容出现在刷新的页面上,而不是仅仅更新 DIV。
代码:
<script>
$(function () {
$('form').submit(function () {
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
$('#result').html(result);
document.getElementById('contactForm').style.display = "none";
}
});
}
return false;
});
});
</script>
当脚本延迟时,如何更新此 jquery 代码才能正常工作?
最佳答案
我建议不要在 jQuery.js 引用中使用 defer
。 jQuery 插件依赖于首先加载的主 jQuery 库。
While there are ways to get around this坦率地说,在大多数情况下它们都显得笨重且过于复杂。
关于javascript - 切换到 JS Defer 转换 jquery ajax 重新加载整个页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50102635/