最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to execute code after "deferred" script is loaded and executed? - Stack Overflow

programmeradmin1浏览0评论

If scripts are loaded synchronously (incl. jQuery), then startup code I use is the following:

<script>
    $(window).load(function () {
        // some startup code
    });
</script>

Now scripts are deferred:

<script defer type="text/javascript" src="//cdnjs.cloudflare/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script defer type="text/javascript" src="...

How do I rewrite my startup code so it executes after deferred scripts are loaded and processed?

If scripts are loaded synchronously (incl. jQuery), then startup code I use is the following:

<script>
    $(window).load(function () {
        // some startup code
    });
</script>

Now scripts are deferred:

<script defer type="text/javascript" src="//cdnjs.cloudflare./ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script defer type="text/javascript" src="...

How do I rewrite my startup code so it executes after deferred scripts are loaded and processed?

Share Improve this question asked Jan 27, 2020 at 18:54 Denis KulaginDenis Kulagin 8,98719 gold badges71 silver badges137 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

The approach I've used is to listen to the 'load' event of that specific script tag - once it's done and good to go, the event will fire.

theScript.addEventListener('load', function () {
    console.log(jQuery.fn.jquery);
});
<script defer id='theScript' type="text/javascript" src="//cdnjs.cloudflare./ajax/libs/jquery/2.1.4/jquery.min.js"></script>

this of course is easier by simply adding an onload to the tag

<script defer src="foo.js" onload="callback()"></script>

Your callback can trigger an event. Theoretically you can use the DOMContentLoaded event but I've had some trouble with js not being fully available when this fires

发布评论

评论列表(0)

  1. 暂无评论