Documentation JavaScript

JavaScript

Overview #

Tips and best practices for incorporating JavaScript files into your site:

  • Use wp_register_script() and wp_enqueue_script() to initialize your Javascript files. This ensures compatibility with other plugins and avoids conflicts.
  • As with everything, prefix your script slugs when registering or enqueuing them.
  • The jQuery version that is packaged with WordPress is in compatibility mode. This means that jQuery() needs to be explicitly used, not the $() short form.
  • Avoid usage of scripts not hosted on WordPress.com. There is a comprehensive list of scripts included. All WordPress.com scripts are served by a CDN.
  • If you need to register a script that is not part of WordPress, or your your theme, make sure to use a packed version if available and make sure that their servers are up for the traffic you will request from them. Fail gracefully.
  • Adding a version to the script when enqueueing isn’t necessary. When we concatenate files, we append the filemtime of the last updated file as a cache buster. If the file isn’t concatenated for some reason, we just use the file’s mtime.

↑ Top ↑

Debugging JavaScript #

If you encounter a problem related to JavaScript, there are a number of recommendations and available resources for troubleshooting the issue and making sure you have complete information if you open a ticket to report it to us.

  • If you’re using any kind of ad blocker or other browser plugin that might modify JS, try turning it off and seeing if the results change
  • Use your browser’s built-in developer tools, or freely available developer tool add-ons, to view details of the JS running on your site and any errors it might be producing:
  • Add debugging code to your JavaScript to confirm it’s working as expected; display the contents of key variables, alert when the code reaches a critical point in its logic, etc.
  • The Google Chrome Developer Tools in particular have some very useful tools for debugging JavaScript issues: inspecting sources, setting breakpoints, controlling execution, etc.

If you do report the issue to us, please make sure to include as much of the information revealed by these tools as possible in your request.