此代码段在本地主机上运行良好,但在服务器上不运行。多次刷新后,j查询将正确加载,然后将按预期工作。 jQuery在页面加载时异步加载,并花费更多时间加载页面。
如何使jQuery在不刷新页面的情况下正确加载,以及如何减少页面末尾所有脚本的加载时间
<noscript id="async-styles">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/css/bootstrap-datepicker.css" />
<link rel="stylesheet" type="text/css" href="css/style.css" />
<link rel="stylesheet" href="css/star-rating.min.css">
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-switch/3.0.1/css/bootstrap3/bootstrap-switch.css" rel="stylesheet" crossorigin="anonymous">
</noscript>
<script> // The CSS mentioned in "async-styles" will be loaded and styles will be applied.
var loadDeferredStyles = function() {
var addStylesNode = document.getElementById("async-styles");
var replacement = document.createElement("div");
replacement.innerHTML = addStylesNode.textContent;
document.body.appendChild(replacement)
addStylesNode.parentElement.removeChild(addStylesNode);
};
var raf = requestAnimationFrame || mozRequestAnimationFrame ||
webkitRequestAnimationFrame || msRequestAnimationFrame;
if (raf) raf(function() {
window.setTimeout(loadDeferredStyles, 0);
});
else window.addEventListener('load', loadDeferredStyles);
</script>
<script async src="js/jquery-3.2.1.min.js" onLoad="loadOtherScripts();"></script>
<script>
function loadScript(src) {
return new Promise(function (resolve, reject) {
var s;
s = document.createElement('script');
s.src = src;
s.onload = resolve;
s.onerror = reject;
document.head.appendChild(s);
});
}
function loadOtherScripts() {
loadScript('js/moment.min.js')
.then(function() {
Promise.all([ loadScript('https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.3.0/js/bootstrap-datepicker.js'),loadScript('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js'),loadScript('js/daterangepicker.js'),loadScript('js/star-rating.min.js'),loadScript('js/sidebar.js'),loadScript('https://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.9.1/jquery.tablesorter.min.js'),loadScript('https://cdnjs.cloudflare.com/ajax/libs/bootstrap-switch/3.0.1/js/bootstrap-switch.js')]).then(function () {
intialFunction();
}).catch(function (error) {
// console.log('some error!' + error)
})
}).catch(function (error) {
// console.log('Moment call error!' + error)
})
}
</script>
答案 0 :(得分:-1)
我们可以将其最小化并捆绑在一起,然后一次性加载,而不是一一加载。这将减少每个脚本的大小和网络往返。