简体   繁体   English

如何避免多次加载 jQuery 脚本?

[英]How can I avoid jQuery scripts being loaded multiple times?

On my site, I load jQuery UI script using the following code:在我的网站上,我使用以下代码加载 jQuery UI 脚本:

wp_enqueue_script('nf-jquery-ui','http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.5/jquery-ui.min.js')

In my plugin I use the following code:在我的插件中,我使用以下代码:

wp_enqueue_script('wp_filebrowser-jqueryui','http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.5/jquery-ui.js')

The result is that both these lines are added to my header - and loading a script twice is not very good.结果是这两行都添加到我的标题中 - 两次加载脚本不是很好。

Yes, I know I can remove it from either my plugin or my site.是的,我知道我可以从我的插件或我的网站中删除它。 But the point is that anyone can download my plugin, and they might already be loading the jQuery UI script.但关键是任何人都可以下载我的插件,而且他们可能已经在加载 jQuery UI 脚本。

How can I avoid having a script being added twice?如何避免脚本被添加两次?

You could deregister the first script by putting this line in your plugin...您可以通过将此行放在您的插件中来取消注册第一个脚本...

wp_deregister_script( 'nf-jquery-ui');

before you call your 'enqueue script'在你调用你的“入队脚本”之前

wp_enqueue_script('wp_filebrowser-jqueryui','http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.5/jquery-ui.js')

This should remove the first jQuery call on all pages that use your plugin.这应该会删除所有使用您插件的页面上的第一个 jQuery 调用。

TheWP API states the first param is a handler. WP API 声明第一个参数是处理程序。 That one is probably used so a script is only inserted once (although I can not say for sure).可能使用了那个脚本,所以脚本只插入一次(虽然我不能肯定地说)。

It also defines handlers for jQuery and jQuery UI which you should probably use.它还为您可能应该使用的 jQuery 和 jQuery UI 定义了处理程序 Those handlers are for included scripts and jQuery as well as jQuery-ui is listed there.这些处理程序用于包含的脚本,其中列出了 jQuery 和 jQuery-ui。 If you want to update consider passing the version to the wp_-function or just replacing the jQuery script file that's already in use / packaged with wp.如果您想更新,请考虑将版本传递给 wp_-function 或仅替换已使用 / 与 wp 打包的 jQuery 脚本文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM