This guide demonstrates how to use beautify.js
to clean up messy jQuery code, improving readability and maintainability. Dynamically generated JavaScript/jQuery often lacks formatting, making it difficult to work with. beautify.js
solves this by automatically formatting the code. This is particularly useful for function demos where the code needs to be presentable. The "View Code" button on example pages showcases this in action.
Live Demo & Download: [Link to Demo] [Link to Download]
Implementation Steps:
Download: Obtain the beautify.js
package from GitHub. Remove unnecessary components like obfuscation unpackers to streamline the code.
Modify: Adapt the code to your project. The example includes a parameter to target specific elements, iterating through elements with the class "raw" containing the jQuery code.
Integration: Include the beautifier call within a DOM ready function. Optionally, integrate a syntax highlighter (many are available) for enhanced readability.
Code Example:
Include these scripts:
Wrap your jQuery code within <code><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false"></pre><div class="contentsignin">Copy after login</div></div>
tags with the class "raw":
<pre class='brush:php;toolbar:false;'> // Your jQuery code here...
The modified beautify()
mybeautifier.js
The modified beautify()
function (located in
var the = { beautify_in_progress: false }; // Chrome string handling optimization (if needed) if (/chrome/.test(navigator.userAgent.toLowerCase())) { String.prototype.old_charAt = String.prototype.charAt; String.prototype.charAt = function (n) { return this.old_charAt(n); } } function unpacker_filter(source) { // ... (comment handling logic remains unchanged) ... } function beautify(elem) { if (the.beautify_in_progress) return; the.beautify_in_progress = true; var source = $(elem).html(); // ... (settings and beautification logic remains largely unchanged) ... }
Finally, call the beautifier within a DOM ready function:
$(document).ready(function() { $('.raw').each(function() { beautify(this); }); });
JS Beautify FAQ:
JS Beautify
This section answers common questions about
The above is the detailed content of Beautify Your jQuery Code Using beautify.js. For more information, please follow other related articles on the PHP Chinese website!