Can I add ready() in the top of a jQuery plugin?
I am trying to write a plugin, following the guidelines from jQuery site.
I am also trying to incorporate everything into it, including creating new div elements.
Those div's need to be created on document ready, so I am trying to figure the best options here.
This is what I currently have and it w开发者_如何学JAVAorks fine, but it doesn't looks right for some reason, even though I cannot see anywhere that it shouldn't be done that way.
Is there a better way to do it?
$(document).ready(function() {
var message_bar = "<div id="something"></div>";
$('body').prepend(message_bar);
});
(function( $ ){
$.fn.displayMessage = function(options) {
...
If it's a plugin, you should really allow the user of the plugin the choice of when to initialise it.
I'd recommend creating an init
function that the user can call explicitly or is called implicitly when the plugin is instantiated.
In the docs, you can stipulate that the plugin shouldn't be initialised until the document is ready... or you could write some code to check the state of the document and add your initialisation code to the ready()
queue.
Putting the ready function into an init method has some advantages:
Pages that load all the plugins but do not need them can easily disable the plugin.
Scripts that execute your displayMessage() method on ready and run before your plugin runs will put displayMessage() in the ready queue earlier than the plugin's own ready script. When the ready event fires the functions are called in the wrong order.
精彩评论