I have the following html code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="https://cdn.jsdelivr.net/blazy/1.8.2/blazy.min.js" defer></script>
    <script src="https://code.jquery.com/jquery-2.1.4.min.js" integrity="sha256-8WqyJLuWKRBVhxXIL1jBDD7SDxU936oZkCnxQbWwJVw=" crossorigin="anonymous" defer></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lightbox2/2.9.0/js/lightbox.min.js" defer></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous" defer></script>
    <!-- 26 dec flexslider js -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/flexslider/2.6.3/jquery.flexslider.min.js" defer></script>
    <script defer>
    (function($) {
        $(document).ready(function() {
            //do something with b-lazy plugin, lightbox plugin and then with flexslider
        });
    })(jQuery);
    </script>
</head>
<body>
</body>
</html>

我得到一个错误,说jQuery没有定义.现在,即使我从内联JS代码中删除了defer,它也表示jQuery是未定义的.出于某种原因,我必须保持jQuery插件在头脑中,并保持我的JS代码内联.我的问题是:

  1. 为什么内联Javascript代码上有defer个属性时不会延迟

  2. 有没有办法在我的内联Javascript代码中模仿延迟行为?如果需要的话,我可以把它放在车身标签的末尾.

推荐答案

The scripts with the defer attribute load in the order they are specified, but not before the document itself has been loaded. As defer has no effect on script tags unless they also have the src attribute, the first script that gets executed is your inline script. So at that time jQuery is not loaded yet.

You can solve this in at least two ways:

  • 将内联脚本放在一个.js文件中,并使用src属性引用它(除了已经存在的defer属性之外),或者

  • 让您的内联脚本等待加载文档和延迟的脚本.DOMContentLoaded事件将在该事件发生时触发:

    <script>
        window.addEventListener('DOMContentLoaded', function() {
            (function($) {
                //do something with b-lazy plugin, lightbox plugin and then with flexslider
            })(jQuery);
        });
    </script>
    

NB: Notice that in the latter case $(document).ready(function() is not included any more, as that would wait for the same event (DOMContentLoaded). You could still include it like you had in your original code, but then jQuery would just execute the callback immediately, which makes no practical difference.

Jquery相关问答推荐

ASP.NET Core 6 jQuery 验证不起作用

jQuery:在mousemove事件期间检测按下的鼠标按钮

jQuery.parseJSON 单引号与双引号

jQuery 绑定点击 *ANYTHING* 但 *ELEMENT*

jQuery - 获取 ajax POST 的表单值

使用 JQuery 清除下拉列表

如何在 Slick 轮播项目之间添加空格

jQuery/JavaScript 碰撞检测

谷歌图表重绘/zoom 窗口调整大小

jQuery Force 为 iframe 设置 src 属性

使用 MVC、C# 和 jQuery 导出为 CSV

jQuery 不会从 AJAX 查询中解析我的 JSON

如何在javascript中获取json键和值?

订单对象是否由指定的 jQuery Select 器返回?

jquery,id内类的 Select 器

jquery更改div类的样式属性

我可以通过 JavaScript 禁用 CSS :hover 效果吗?

jquery $(window).width() 和 $(window).height() 在未调整视口大小时返回不同的值

删除所有以某个字符串开头的类

如何在 DOM 中移动 iFrame 而不会丢失其状态?