是否有可能等到所有javascript文件都被加载后再执行javascript代码?

时间:2022-08-23 18:14:04

We have several JavaScript files which we load at the bottom of the master page. However, I have the situation that I need to perform some JavaScript before the other scripts are loaded. Is it possible to wait till all the JavaScript files are loaded and then execute some JavaScript code?

我们有几个JavaScript文件,我们加载在母版页的底部。但是,在我加载其他脚本之前,我需要执行一些JavaScript。是否可以等到加载所有JavaScript文件然后执行一些JavaScript代码?

I thought $(document).ready() did this, but as it turns out, it doesn't. Of course we can move the script files from the bottom to the top, but I am wondering if it's possible what I want.

我以为$(document).ready()做到了这一点,但事实证明,它没有。当然我们可以将脚本文件从底部移到顶部,但我想知道它是否可能是我想要的。

3 个解决方案

#1


62  

You can use

您可以使用

$(window).on('load', function() {
    // your code here
});

Which will wait until the page is loaded. $(document).ready() waits until the DOM is loaded

这将等到页面加载。 $(document).ready()等待DOM加载

#2


29  

You can use .getScript() and run your code after it loads:

您可以使用.getScript()并在加载后运行代码:

 $.getScript("my_lovely_script.js", function(){

    alert("Script loaded and executed.");
    // here you can use anything you defined in the loaded script

 });

You can see a better explanation here: How do I include a JavaScript file in another JavaScript file?

您可以在此处看到更好的解释:如何在另一个JavaScript文件中包含JavaScript文件?

#3


20  

You can use <script>'s defer attribute. It specifies that the script will be executed when the page has finished parsing.

您可以使用

<script defer src="path/to/yourscript.js">

A nice article about this: http://davidwalsh.name/script-defer

一篇很好的文章:http://davidwalsh.name/script-defer

Browser support seems pretty good: http://caniuse.com/#search=defer

浏览器支持似乎很不错:http://caniuse.com/#search=defer

#1


62  

You can use

您可以使用

$(window).on('load', function() {
    // your code here
});

Which will wait until the page is loaded. $(document).ready() waits until the DOM is loaded

这将等到页面加载。 $(document).ready()等待DOM加载

#2


29  

You can use .getScript() and run your code after it loads:

您可以使用.getScript()并在加载后运行代码:

 $.getScript("my_lovely_script.js", function(){

    alert("Script loaded and executed.");
    // here you can use anything you defined in the loaded script

 });

You can see a better explanation here: How do I include a JavaScript file in another JavaScript file?

您可以在此处看到更好的解释:如何在另一个JavaScript文件中包含JavaScript文件?

#3


20  

You can use <script>'s defer attribute. It specifies that the script will be executed when the page has finished parsing.

您可以使用

<script defer src="path/to/yourscript.js">

A nice article about this: http://davidwalsh.name/script-defer

一篇很好的文章:http://davidwalsh.name/script-defer

Browser support seems pretty good: http://caniuse.com/#search=defer

浏览器支持似乎很不错:http://caniuse.com/#search=defer