我目前正在寻求通过确保公司 Logo 在 JavaScript 之前下载来改善 Web 应用程序的感知。
为此,我将 JavaScript 引用移至公司 Logo 的 img
元素下方。
例如:
<img src="/Images/Logo.jpg" alt="My Company"/>
<script type="/Scripts/MyScripts.js"></script>
在查看 Google Chrome 开发者工具时,我可以看到对 Logo 的调用已发出,但它仍保持“待处理”状态,直到下载页面上的所有 javascript。
为什么会发生这种情况?如何确保公司 Logo 先于 JavaScript 加载?
最佳答案
尝试使用$(window).load
如果您使用的是 jQuery,则适用于您的脚本。
$( window).load(function() {
//put js code here
});
根据this site :
The window load event executes a bit later when the complete page is fully loaded, including all frames, objects and images. Therefore functions which concern images or other page contents should be placed in the load event for the window or the content tag itself.
至于您必须使用 <script src='path/to/file'>
添加到站点的单独文件,我建议使用 $.getScript
.
$.getScript("path/to/file");
这是 $.getScript
manual .
关于javascript - 如何在javascript之前加载图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28738525/