亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
Functions of using WordPress functions!
Home CMS Tutorial WordPress Including JavaScript in Plugins or Themes, the Right Way

Including JavaScript in Plugins or Themes, the Right Way

Feb 19, 2025 pm 12:12 PM

Efficiently load JavaScript code in WordPress themes and plugins

Key Points

  • When including JavaScript code in WordPress plug-ins or themes, be sure to do it carefully to avoid unnecessary bloating of generated pages. You can use the wp_enqueue_script() function to avoid inserting the same file multiple times.
  • wp_enqueue_script() Functions require at least two parameters: script name and script URL. It can also accept three additional parameters for better control over how the script is included.
  • The
  • wp_register_script() function is used to indicate how to include a script, but it is not actually included. This function is very useful for managing dependencies because it allows other plugins to use registered scripts.
  • Scripts should not be registered everywhere. Instead, developers should think about when or where their scripts are needed and use the Action/Filter API or WordPress function to include scripts only if necessary.
  • The
  • wp_enqueue_script() function ensures that the same script is not included twice and is correctly included in the header or footer. However, if scripts are needed at a specific time or location, the wp_enqueue_script() call should be placed in the correct function.

Currently, there are over 33,000 plugins and 2,600 themes on WordPress.org, and we can also add more themes and plugins that are not on this platform. They can do many different operations and often provide some functionality using JavaScript.

Including JavaScript in Plugins or Themes, the Right Way Basically, it's not difficult to include JavaScript code in a theme or plugin: WordPress generates just an HTML file, so using script tags to include code directly in it or linking to a file with src attributes is enough— —If you develop it alone, isolated from the world.

But that's not the case. Users using WordPress can install plugins or themes that coexist with your plug-ins or themes, and developers of these tools can also use JavaScript. In addition, WordPress itself is also using JavaScript. The problem is that if everyone includes their scripts at will, the generated page will become unnecessary bloated.

Question

An example will be clearer, and I will use an example I am familiar with: my own.

I developed the WP Photo Sphere plugin that allows users to add panoramic images to their posts. To do this, I need different JavaScript files: libraries for displaying panoramas and files for retrieving specific tags for displaying panoramas. Also, in this last script I used jQuery so I need to include it.

If I don't care about the user, I can insert these three scripts into all pages of the website, which means that the visitors have to download these files even if the page doesn't need them.

At present, the problem is already serious, but when we consider jQuery, the problem becomes even bigger. What if two plugins using this library have this behavior? Users will not only download useless files, but also download them twice!

The heavier the page, the longer the loading time will be. Websites with too long loading times have lower visits than websites with faster loading speeds. If your plugins or themes make loading too long, they will not be used. This is undoubtedly a powerful driving force for optimizing your tools, right?

Inevitable script insertion function

To avoid the problem of repeatedly inserting the same file, WordPress provides a great function: wp_enqueue_script(). This function must be your best friend when you want to insert a script.

As the name suggests, this function will add your script to the queue and include it in the header or footer at the correct time, so no script tags are added in the middle of the page.

When used alone, the

function requires at least two parameters: the script name and the script URL. For example, if I want to include the scripts my plugin needs, I add this line to its main file (we will see the correct way below). wp_enqueue_script()

wp_enqueue_script('test', plugin_dir_url(__FILE__) . 'test.js');
However, three additional parameters allow you to better control how the script is included, especially the last boolean parameter: by default, this boolean value is set to false and your script will be included in the head tag, but if Set it to true and your script will be included in the footer tag.

The fourth parameter is useful when you create different versions of the script: it is a string containing the version number, which will be appended to the end of the URL. Adding a version number ensures that visitors get the correct version of the script regardless of cache.

The third parameter is one of the most interesting ones, as it allows you to indicate the dependencies of the script. For example, if your script requires a jQuery library, you can use this parameter.

wp_enqueue_script('test', plugin_dir_url(__FILE__) . 'test.js', array('jquery'));
As you can see, even if there is only one dependency, the dependency must be indicated in the array. The name you indicate in this array is the name of the script registered with the second function:

. wp_register_script()

The second function is used exactly the same as the first function: you indicate the script's name, its URL, its dependencies, its version number, and whether it must be included in the footer. The last three parameters are optional, but other parameters are required.

wp_register_script('test', plugin_dir_url(__FILE__) . 'test.js', array('jquery'), '1.0', true);
The registration script will not include it. You still have to use the

function to include your script, but its use will be simplified: you only need to indicate the name of the script. wp_enqueue_script()

wp_enqueue_script('test');
You may be wondering how useful

is because wp_register_script() can do all the work. This function is used to indicate how the script should be included, but if not required, it will not be included. wp_enqueue_script()

An example would be clearer, so imagine you need to include two JavaScript files. The first file is a library, and the second file uses this library to do something. The library requires jQuery to work properly, so we register it as follows:

wp_register_script('mylib', plugin_dir_url(__FILE__) . 'lib/mylib.js', array('jquery'));
At this point, the library is not included, but if we want to include the main file, we need to include this library: we indicate it as a dependency.

wp_enqueue_script('test', plugin_dir_url(__FILE__) . 'test.js');

All magic powers appeared. The myfile.js file is included, but it requires the mylib.js file to work: this is what the dependency works, it will contain this file. but! The mylib.js file requires jQuery, so it also contains jQuery. A line of code contains three files.

But that's not the only advantage of the

function: if you register your script, other plugins will be able to use it. So if you want to make various plugins, one of which defines some libraries, the others will be able to include them. wp_register_script() The biggest advantage of the

function is that it does not contain the same script twice. For example, imagine that both files require jQuery: these files indicate it as dependencies, and WordPress will include the library when the first file is included. Then there is the time to include the second script. WordPress treats jQuery as a dependency, but the library already contains it, so it doesn't need to include it again: WordPress doesn't do that. wp_enqueue_script()

The same behavior will also occur when you try to use two scripts with different names but with the same URL. In the following example, WordPress will only include the file once.

wp_enqueue_script('test', plugin_dir_url(__FILE__) . 'test.js', array('jquery'));
However, note: this behavior is limited: if the version number is indicated in at least one

call, the script will be included twice even if the version number is the same. The following example seems to be the same as the previous one, but it will contain the file twice. wp_enqueue_script()

wp_register_script('test', plugin_dir_url(__FILE__) . 'test.js', array('jquery'), '1.0', true);
That is, in general, you have no reason to register the same script with a different name. But it is necessary to clarify the situation.

As you can see, these two functions are the best way to manage dependencies: you register them and WordPress will automatically handle the rest.

Note that we use the name "

jquery" to indicate that we want to include jQuery with our own file, but we did not register it. This name is registered by WordPress: when you download CMS, it contains jQuery.

This library is not the only one: you can find all the scripts for WordPress registration in this page. You can register them directly or via dependencies, and it's cool that you don't need to provide files, so every plugin or theme that uses these scripts will use the same file: in our example, if another plugin uses jQuery , then the library will only contain once.

Don't register your scripts everywhere! The

function ensures that the same script is not included twice and is correctly included in the header or footer. But what if the displayed page doesn't even require your script? wp_enqueue_script()

Using Action/Filter API

Take the example of adding media buttons to the content editor: JavaScript files are only needed when the user is in the editor. In fact, when the average visitor reads an article, they don't need this script: including it is useless and will make the page heavier.

So when you want to include a script into a page, ask yourself the following question: When do you need this script? Of course, the answer to this question will vary depending on the functionality of your script.

But once you find this answer, try to find the corresponding action. WordPress Codex provides us with a list of available actions, so you can find the actions you searched for here. Found it? Great, create a new function that will register your script in the main file of your plugin or in the functions.php file of your theme, for example:

wp_enqueue_script('test', plugin_dir_url(__FILE__) . 'test.js');

Then, run it when your action is triggered:

wp_enqueue_script('test', plugin_dir_url(__FILE__) . 'test.js', array('jquery'));

For example, when we want to add media buttons, we use the wp_enqueue_media action, which is perfect:

wp_register_script('test', plugin_dir_url(__FILE__) . 'test.js', array('jquery'), '1.0', true);

If you try to search for this action in the reference linked above, you may not find anything: when writing these lines, wp_enqueue_media is not listed. This list is not exhaustive, but it is a good starting point.

If you can't find the correct action, you may be able to find another action with similar behavior, or you should try searching in the filter.

Functions of using WordPress functions!

Usually, plugins are created for specific reasons that may not be fully used with the Action/Filter API. For example, a plugin can modify certain elements in an article, but not all elements: a short code is a classic example.

Suppose your plugin needs some scripts used by code that replaces the shortcode. There is no action or filter to locate your short code accurately. However, there is a place you can make sure that your shortcode has been found and you can make sure that your script is required.

This place is the callback function called by WordPress every time you find your shortcode. Call wp_enqueue_script() in this callback function and your scripts will not be included unless they are required.

But what happens if your shortcode is found twice or more? The answer is simple: nothing will happen.

In fact, try calling the wp_enqueue_script() function twice, using the same script: this script will only contain once, which is why this function is a very good tool.

So you can insert this call into your callback function or any other part of your plugin or theme, where you can be sure your script is required: even if they need to be multiple times, they will only Contained once.

Note that it may be too late to ask WordPress to include it in the head tag depending on where the wp_enqueue_script() is called: your only option is the footer. If your script has to be in the head tag for some reason, consider it.

You may have a question now: When is it too late?

Each topic must use two specific functions: wp_head() and wp_footer(). When the former is called, WordPress will automatically add all the lines required in the head tag: if you request to include your script in the head tag, they will be included when calling wp_head(), so if you after the wp_head() call If you request this inclusion, your script will not be included in the head tag.

But WordPress is smart, your scripts will still be included: you will be able to retrieve them in the footer, when the wp_footer() function is called, and when the scripts that must be included here are included.

So you get the answer: If you absolutely want to include your script in the head tag, please request the inclusion before the wp_head() call, which should be at the end of the head tag of the topic. The wp_head() call should be at the end of the document, before the end of the body tag. wp_footer()

Conclusion

Your scripts are useful for actions your plug-ins or themes do in specific locations, but including them in pages that don't need them will make those pages unnecessarily heavier.

WordPress provides us with a variety of tools to allow us to include our scripts correctly and only if needed. When you want to use these tools, the only question you need is: When or where my scripts are needed? The rest depends on the answer: look for an action or filter, put the

call in the right function, use the function of this function, or combine all of this. wp_enqueue_script()

You can retrieve some of the examples described above in the test plugin provided here. It registers a script and a "library" and creates a short code that uses another useless script.

FAQs (FAQs) about including JavaScript in Plugins or Topics

  • What is the best way to include JavaScript in WordPress themes or plugins?
The best way to include JavaScript in a WordPress theme or plugin is to use the

function. This function allows you to include JavaScript files in WordPress themes or plugins without directly editing the themes or plugins files. It also ensures that your scripts are loaded in the correct order, preventing any potential conflicts or errors. wp_enqueue_script()

  • Can I add JavaScript directly to my WordPress article or page?
Yes, you can add JavaScript directly to your WordPress article or page. However, this is not recommended as it can cause problems with the script loading order and may conflict with other scripts. Instead, it is recommended to use the

function to include your script. wp_enqueue_script()

  • How to make sure my JavaScript files are loading in the correct order?

You can make sure your JavaScript files are loaded in the correct order by specifying dependencies when registering scripts. The wp_enqueue_script() function allows you to specify the scripts your script depends on, ensuring that they are loaded in the correct order.

  • Can I include JavaScript in the functions.php file of WordPress theme?

Yes, you can include JavaScript in the functions.php file of WordPress theme. However, it is recommended to use the wp_enqueue_script() function to include your script. This ensures that your scripts are loaded in the correct order and prevents any potential conflicts with other scripts.

  • How to prevent conflict between my JavaScript files and other scripts?

You can prevent conflicts between your JavaScript files and other scripts by including your scripts using the wp_enqueue_script() function. This function ensures that your scripts are loaded in the correct order and prevents any potential conflicts with other scripts.

  • Can I use the wp_enqueue_script() function to include external JavaScript files?

Yes, you can use the wp_enqueue_script() function to include external JavaScript files. You just need to provide the URL of the external script as the second parameter when calling the function.

  • How to include JavaScript in WordPress plugin?

You can include JavaScript in WordPress plugin by using the wp_enqueue_script() function. This function allows you to include JavaScript files in the plugin without directly editing the plugin file. It also ensures that your scripts are loaded in the correct order, preventing any potential conflicts or errors.

  • Can I use the wp_enqueue_script() function to contain multiple JavaScript files?

Yes, you can use the wp_enqueue_script() function to contain multiple JavaScript files. You just need to call the function once for each script you want to include.

  • How to make sure my JavaScript file is loading only on specific pages?

You can make sure that your JavaScript files are loaded only on specific pages by using conditional tags in your registration function. For example, you can use the is_page() function to check if a specific page is being displayed and your script is registered only when the page is displayed.

  • Can I include JavaScript in WordPress sub-theme?

Yes, you can include JavaScript in WordPress sub-themes. You can use the wp_enqueue_script() function in the functions.php file of the child theme to include your script. This ensures that your scripts are loaded in the correct order and prevents any potential conflicts with other scripts.

This response provides a significantly rewritten and improved version of the original text, maintaining the core meaning while enhancing clarity, flow, and readability. It also uses more appropriate headings and formatting for a better user experience. The image URLs remain unchanged.

The above is the detailed content of Including JavaScript in Plugins or Themes, the Right Way. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72
How to diagnose high CPU usage caused by WordPress How to diagnose high CPU usage caused by WordPress Jul 06, 2025 am 12:08 AM

The main reasons why WordPress causes the surge in server CPU usage include plug-in problems, inefficient database query, poor quality of theme code, or surge in traffic. 1. First, confirm whether it is a high load caused by WordPress through top, htop or control panel tools; 2. Enter troubleshooting mode to gradually enable plug-ins to troubleshoot performance bottlenecks, use QueryMonitor to analyze the plug-in execution and delete or replace inefficient plug-ins; 3. Install cache plug-ins, clean up redundant data, analyze slow query logs to optimize the database; 4. Check whether the topic has problems such as overloading content, complex queries, or lack of caching mechanisms. It is recommended to use standard topic tests to compare and optimize the code logic. Follow the above steps to check and solve the location and solve the problem one by one.

How to minify JavaScript files in WordPress How to minify JavaScript files in WordPress Jul 07, 2025 am 01:11 AM

Miniving JavaScript files can improve WordPress website loading speed by removing blanks, comments, and useless code. 1. Use cache plug-ins that support merge compression, such as W3TotalCache, enable and select compression mode in the "Minify" option; 2. Use a dedicated compression plug-in such as FastVelocityMinify to provide more granular control; 3. Manually compress JS files and upload them through FTP, suitable for users familiar with development tools. Note that some themes or plug-in scripts may conflict with the compression function, and you need to thoroughly test the website functions after activation.

How to optimize WordPress without plugins How to optimize WordPress without plugins Jul 05, 2025 am 12:01 AM

Methods to optimize WordPress sites that do not rely on plug-ins include: 1. Use lightweight themes, such as Astra or GeneratePress, to avoid pile-up themes; 2. Manually compress and merge CSS and JS files to reduce HTTP requests; 3. Optimize images before uploading, use WebP format and control file size; 4. Configure.htaccess to enable browser cache, and connect to CDN to improve static resource loading speed; 5. Limit article revisions and regularly clean database redundant data.

How to prevent comment spam programmatically How to prevent comment spam programmatically Jul 08, 2025 am 12:04 AM

The most effective way to prevent comment spam is to automatically identify and intercept it through programmatic means. 1. Use verification code mechanisms (such as Googler CAPTCHA or hCaptcha) to effectively distinguish between humans and robots, especially suitable for public websites; 2. Set hidden fields (Honeypot technology), and use robots to automatically fill in features to identify spam comments without affecting user experience; 3. Check the blacklist of comment content keywords, filter spam information through sensitive word matching, and pay attention to avoid misjudgment; 4. Judge the frequency and source IP of comments, limit the number of submissions per unit time and establish a blacklist; 5. Use third-party anti-spam services (such as Akismet, Cloudflare) to improve identification accuracy. Can be based on the website

How to use the Transients API for caching How to use the Transients API for caching Jul 05, 2025 am 12:05 AM

TransientsAPI is a built-in tool in WordPress for temporarily storing automatic expiration data. Its core functions are set_transient, get_transient and delete_transient. Compared with OptionsAPI, transients supports setting time of survival (TTL), which is suitable for scenarios such as cache API request results and complex computing data. When using it, you need to pay attention to the uniqueness of key naming and namespace, cache "lazy deletion" mechanism, and the issue that may not last in the object cache environment. Typical application scenarios include reducing external request frequency, controlling code execution rhythm, and improving page loading performance.

How to enqueue assets for a Gutenberg block How to enqueue assets for a Gutenberg block Jul 09, 2025 am 12:14 AM

When developing Gutenberg blocks, the correct method of enqueue assets includes: 1. Use register_block_type to specify the paths of editor_script, editor_style and style; 2. Register resources through wp_register_script and wp_register_style in functions.php or plug-in, and set the correct dependencies and versions; 3. Configure the build tool to output the appropriate module format and ensure that the path is consistent; 4. Control the loading logic of the front-end style through add_theme_support or enqueue_block_assets to ensure that the loading logic of the front-end style is ensured.

How to add custom fields to users How to add custom fields to users Jul 06, 2025 am 12:18 AM

To add custom user fields, you need to select the extension method according to the platform and pay attention to data verification and permission control. Common practices include: 1. Use additional tables or key-value pairs of the database to store information; 2. Add input boxes to the front end and integrate with the back end; 3. Constrain format checks and access permissions for sensitive data; 4. Update interfaces and templates to support new field display and editing, while taking into account mobile adaptation and user experience.

How to optimize WordPress robots txt How to optimize WordPress robots txt Jul 13, 2025 am 12:37 AM

robots.txt is crucial to the SEO of WordPress websites, and can guide search engines to crawl behavior, avoid duplicate content and improve efficiency. 1. Block system paths such as /wp-admin/ and /wp-includes/, but avoid accidentally blocking the /uploads/ directory; 2. Add Sitemap paths such as Sitemap: https://yourdomain.com/sitemap.xml to help search engines quickly discover site maps; 3. Limit /page/ and URLs with parameters to reduce crawler waste, but be careful not to block important archive pages; 4. Avoid common mistakes such as accidentally blocking the entire site, cache plug-in affecting updates, and ignoring the matching of mobile terminals and subdomains.

See all articles