如何链接html文档中的jQuery插件

时间:2021-08-02 08:28:57

I want to link the Social FloatingShare jQuery plugin in HTML document. I have try to link this jQuery plugin, But calling the plugin function floatingShare() is not working as I excepted.

我想在HTML文档中链接Social FloatingShare jQuery插件。我试着链接这个jQuery插件,但调用插件函数floatingShare()不能正常工作。

I have two questions:

我有两个问题:

  1. How to link a jQuery in my html document?
  2. 如何在我的html文档中链接jQuery?

  3. What mistake I have done in my code?
  4. 我在代码中犯了什么错误?

My Source Code:

我的源代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Jquery Plugin</title>
    <style>
        body { margin: 0px; padding: 0px; background: #ccc; }
        .container { height: 500px; width: 1000px; margin: 0px auto; padding: 0px; }
    </style>
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.1.0/css/font-awesome.min.css">
</head>
<body>
<div class="container">
    <script type="text/javascript">
        $(function(){
            $("body").floatingShare();
        });
    </script>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="js/jquery.floating-share.js" type="text/javascript"></script>
</body>
</html>

3 个解决方案

#1


9  

You need to include jquery plugins before its use because all the jQuery or jQuery functions should be available before using, so change the jquery library and script sequence as show below -

您需要在使用之前包含jquery插件,因为所有jQuery或jQuery函数在使用之前都应该可用,因此请更改jquery库和脚本序列,如下所示 -

NOTE - It is good practice to keep script tag directly into <body> or <head> tag instead of any other html element.

注 - 最好将脚本标记直接保存到或标记中,而不是任何其他html元素。

<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
<script src="js/jquery.floating-share.js" type="text/javascript"></script>
<script type="text/javascript">
  $(function(){
   $("body").floatingShare();
  });
</script> 
<div class="container"> 

</div>

</body>

#2


6  

Include all .js files at the end of Body block is a good practice for loading performances. Then, you have to make sure call any JavaScript functions from your references after the page is fully loaded.

在Body块的末尾包含所有.js文件是加载性能的好方法。然后,您必须确保在页面完全加载后从引用中调用任何JavaScript函数。

Two common options I usually choose:

我通常选择的两个常见选项:

Option 1. Include the jQuery library in Head, and keep all other .js files at the end of Body block. In your case, the JavaScript related part code should be as:

选项1.在Head中包含jQuery库,并将所有其他.js文件保存在Body块的末尾。在您的情况下,JavaScript相关的部分代码应为:

    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
    </head>
    <body>
        <div class="container"> 
            <script type="text/javascript">
                $(document).ready(function(){
                    $("body").floatingShare();
                });
            </script> 
        </div>
        <script src="js/jquery.floating-share.js" type="text/javascript"></script>
    </body>

Option 2. Keep all .js files at the end of Body block, then implement $(document).ready() in JavaScript rather than using jQuery library. According to jQuery resource, the equivalent pure JavaScript implementation of $(document).ready() is:

选项2.将所有.js文件保存在Body块的末尾,然后在JavaScript中实现$(document).ready()而不是使用jQuery库。根据jQuery资源,$(document).ready()的等效纯JavaScript实现是:

    var ready = (function(){    

        var readyList,
            DOMContentLoaded,
            class2type = {};
            class2type["[object Boolean]"] = "boolean";
            class2type["[object Number]"] = "number";
            class2type["[object String]"] = "string";
            class2type["[object Function]"] = "function";
            class2type["[object Array]"] = "array";
            class2type["[object Date]"] = "date";
            class2type["[object RegExp]"] = "regexp";
            class2type["[object Object]"] = "object";

        var ReadyObj = {
            // Is the DOM ready to be used? Set to true once it occurs.
            isReady: false,
            // A counter to track how many items to wait for before
            // the ready event fires. See #6781
            readyWait: 1,
            // Hold (or release) the ready event
            holdReady: function( hold ) {
                if ( hold ) {
                    ReadyObj.readyWait++;
                } else {
                    ReadyObj.ready( true );
                }
            },
            // Handle when the DOM is ready
            ready: function( wait ) {
                // Either a released hold or an DOMready/load event and not yet ready
                if ( (wait === true && !--ReadyObj.readyWait) || (wait !== true && !ReadyObj.isReady) ) {
                    // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
                    if ( !document.body ) {
                        return setTimeout( ReadyObj.ready, 1 );
                    }

                    // Remember that the DOM is ready
                    ReadyObj.isReady = true;
                    // If a normal DOM Ready event fired, decrement, and wait if need be
                    if ( wait !== true && --ReadyObj.readyWait > 0 ) {
                        return;
                    }
                    // If there are functions bound, to execute
                    readyList.resolveWith( document, [ ReadyObj ] );

                    // Trigger any bound ready events
                    //if ( ReadyObj.fn.trigger ) {
                    //  ReadyObj( document ).trigger( "ready" ).unbind( "ready" );
                    //}
                }
            },
            bindReady: function() {
                if ( readyList ) {
                    return;
                }
                readyList = ReadyObj._Deferred();

                // Catch cases where $(document).ready() is called after the
                // browser event has already occurred.
                if ( document.readyState === "complete" ) {
                    // Handle it asynchronously to allow scripts the opportunity to delay ready
                    return setTimeout( ReadyObj.ready, 1 );
                }

                // Mozilla, Opera and webkit nightlies currently support this event
                if ( document.addEventListener ) {
                    // Use the handy event callback
                    document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
                    // A fallback to window.onload, that will always work
                    window.addEventListener( "load", ReadyObj.ready, false );

                // If IE event model is used
                } else if ( document.attachEvent ) {
                    // ensure firing before onload,
                    // maybe late but safe also for iframes
                    document.attachEvent( "onreadystatechange", DOMContentLoaded );

                    // A fallback to window.onload, that will always work
                    window.attachEvent( "onload", ReadyObj.ready );

                    // If IE and not a frame
                    // continually check to see if the document is ready
                    var toplevel = false;

                    try {
                        toplevel = window.frameElement == null;
                    } catch(e) {}

                    if ( document.documentElement.doScroll && toplevel ) {
                        doScrollCheck();
                    }
                }
            },
            _Deferred: function() {
                var // callbacks list
                    callbacks = [],
                    // stored [ context , args ]
                    fired,
                    // to avoid firing when already doing so
                    firing,
                    // flag to know if the deferred has been cancelled
                    cancelled,
                    // the deferred itself
                    deferred  = {

                        // done( f1, f2, ...)
                        done: function() {
                            if ( !cancelled ) {
                                var args = arguments,
                                    i,
                                    length,
                                    elem,
                                    type,
                                    _fired;
                                if ( fired ) {
                                    _fired = fired;
                                    fired = 0;
                                }
                                for ( i = 0, length = args.length; i < length; i++ ) {
                                    elem = args[ i ];
                                    type = ReadyObj.type( elem );
                                    if ( type === "array" ) {
                                        deferred.done.apply( deferred, elem );
                                    } else if ( type === "function" ) {
                                        callbacks.push( elem );
                                    }
                                }
                                if ( _fired ) {
                                    deferred.resolveWith( _fired[ 0 ], _fired[ 1 ] );
                                }
                            }
                            return this;
                        },

                        // resolve with given context and args
                        resolveWith: function( context, args ) {
                            if ( !cancelled && !fired && !firing ) {
                                // make sure args are available (#8421)
                                args = args || [];
                                firing = 1;
                                try {
                                    while( callbacks[ 0 ] ) {
                                        callbacks.shift().apply( context, args );//shifts a callback, and applies it to document
                                    }
                                }
                                finally {
                                    fired = [ context, args ];
                                    firing = 0;
                                }
                            }
                            return this;
                        },

                        // resolve with this as context and given arguments
                        resolve: function() {
                            deferred.resolveWith( this, arguments );
                            return this;
                        },

                        // Has this deferred been resolved?
                        isResolved: function() {
                            return !!( firing || fired );
                        },

                        // Cancel
                        cancel: function() {
                            cancelled = 1;
                            callbacks = [];
                            return this;
                        }
                    };

                return deferred;
            },
            type: function( obj ) {
                return obj == null ?
                    String( obj ) :
                    class2type[ Object.prototype.toString.call(obj) ] || "object";
            }
        }
        // The DOM ready check for Internet Explorer
        function doScrollCheck() {
            if ( ReadyObj.isReady ) {
                return;
            }

            try {
                // If IE is used, use the trick by Diego Perini
                // http://javascript.nwbox.com/IEContentLoaded/
                document.documentElement.doScroll("left");
            } catch(e) {
                setTimeout( doScrollCheck, 1 );
                return;
            }

            // and execute any waiting functions
            ReadyObj.ready();
        }
        // Cleanup functions for the document ready method
        if ( document.addEventListener ) {
            DOMContentLoaded = function() {
                document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
                ReadyObj.ready();
            };

        } else if ( document.attachEvent ) {
            DOMContentLoaded = function() {
                // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
                if ( document.readyState === "complete" ) {
                    document.detachEvent( "onreadystatechange", DOMContentLoaded );
                    ReadyObj.ready();
                }
            };
        }
        function ready( fn ) {
            // Attach the listeners
            ReadyObj.bindReady();

            var type = ReadyObj.type( fn );

            // Add the callback
            readyList.done( fn );//readyList is result of _Deferred()
        }
        return ready;
        })();

Then, you can use it like:

然后,您可以使用它:

    ready(function(){
      $("body").floatingShare(); // Assuming jQuery Lib has been included as well
    });

By far, I think option 1 should be more acceptable.

到目前为止,我认为选项1应该更容易接受。

#3


4  

In your code there is a code sequence issue. According to jQuery code Sequence, You have to include jQuery first in your document and then all your custom function as suggested by @Bhushan Kawadkar in above answer.

在您的代码中存在代码序列问题。根据jQuery代码序列,你必须首先在你的文档中包含jQuery,然后在@Bhushan Kawadkar的建议中包含所有自定义函数。

If you still want to add your function in body where you have added it then you can include jQuery in <head> of document e.g

如果您仍想在添加它的正文中添加您的函数,那么您可以在文档的中包含jQuery,例如

<html>
 <head>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
  <script src="http://www.jqueryscript.net/demo/jQuery-Plugin-For-Horizontal-Floating-Social-Share-Bar/js/jquery.floating-share.js" type="text/javascript"></script>
</head>
<body>
 <div class="container"> 
  <script type="text/javascript">
$(function(){
$("body").floatingShare();
});
</script> 
</div>
</body>

And You plugin will start working.

而你的插件将开始工作。

Somehow it is recommended to add scripts(js) in footer to improve render times of your page.

不知何故,建议在页脚中添加脚本(js)以改善页面的渲染时间。

Here is a live demo for you.

这是一个现场演示。

http://codepen.io/anon/pen/AIEnl

#1


9  

You need to include jquery plugins before its use because all the jQuery or jQuery functions should be available before using, so change the jquery library and script sequence as show below -

您需要在使用之前包含jquery插件,因为所有jQuery或jQuery函数在使用之前都应该可用,因此请更改jquery库和脚本序列,如下所示 -

NOTE - It is good practice to keep script tag directly into <body> or <head> tag instead of any other html element.

注 - 最好将脚本标记直接保存到或标记中,而不是任何其他html元素。

<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
<script src="js/jquery.floating-share.js" type="text/javascript"></script>
<script type="text/javascript">
  $(function(){
   $("body").floatingShare();
  });
</script> 
<div class="container"> 

</div>

</body>

#2


6  

Include all .js files at the end of Body block is a good practice for loading performances. Then, you have to make sure call any JavaScript functions from your references after the page is fully loaded.

在Body块的末尾包含所有.js文件是加载性能的好方法。然后,您必须确保在页面完全加载后从引用中调用任何JavaScript函数。

Two common options I usually choose:

我通常选择的两个常见选项:

Option 1. Include the jQuery library in Head, and keep all other .js files at the end of Body block. In your case, the JavaScript related part code should be as:

选项1.在Head中包含jQuery库,并将所有其他.js文件保存在Body块的末尾。在您的情况下,JavaScript相关的部分代码应为:

    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
    </head>
    <body>
        <div class="container"> 
            <script type="text/javascript">
                $(document).ready(function(){
                    $("body").floatingShare();
                });
            </script> 
        </div>
        <script src="js/jquery.floating-share.js" type="text/javascript"></script>
    </body>

Option 2. Keep all .js files at the end of Body block, then implement $(document).ready() in JavaScript rather than using jQuery library. According to jQuery resource, the equivalent pure JavaScript implementation of $(document).ready() is:

选项2.将所有.js文件保存在Body块的末尾,然后在JavaScript中实现$(document).ready()而不是使用jQuery库。根据jQuery资源,$(document).ready()的等效纯JavaScript实现是:

    var ready = (function(){    

        var readyList,
            DOMContentLoaded,
            class2type = {};
            class2type["[object Boolean]"] = "boolean";
            class2type["[object Number]"] = "number";
            class2type["[object String]"] = "string";
            class2type["[object Function]"] = "function";
            class2type["[object Array]"] = "array";
            class2type["[object Date]"] = "date";
            class2type["[object RegExp]"] = "regexp";
            class2type["[object Object]"] = "object";

        var ReadyObj = {
            // Is the DOM ready to be used? Set to true once it occurs.
            isReady: false,
            // A counter to track how many items to wait for before
            // the ready event fires. See #6781
            readyWait: 1,
            // Hold (or release) the ready event
            holdReady: function( hold ) {
                if ( hold ) {
                    ReadyObj.readyWait++;
                } else {
                    ReadyObj.ready( true );
                }
            },
            // Handle when the DOM is ready
            ready: function( wait ) {
                // Either a released hold or an DOMready/load event and not yet ready
                if ( (wait === true && !--ReadyObj.readyWait) || (wait !== true && !ReadyObj.isReady) ) {
                    // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
                    if ( !document.body ) {
                        return setTimeout( ReadyObj.ready, 1 );
                    }

                    // Remember that the DOM is ready
                    ReadyObj.isReady = true;
                    // If a normal DOM Ready event fired, decrement, and wait if need be
                    if ( wait !== true && --ReadyObj.readyWait > 0 ) {
                        return;
                    }
                    // If there are functions bound, to execute
                    readyList.resolveWith( document, [ ReadyObj ] );

                    // Trigger any bound ready events
                    //if ( ReadyObj.fn.trigger ) {
                    //  ReadyObj( document ).trigger( "ready" ).unbind( "ready" );
                    //}
                }
            },
            bindReady: function() {
                if ( readyList ) {
                    return;
                }
                readyList = ReadyObj._Deferred();

                // Catch cases where $(document).ready() is called after the
                // browser event has already occurred.
                if ( document.readyState === "complete" ) {
                    // Handle it asynchronously to allow scripts the opportunity to delay ready
                    return setTimeout( ReadyObj.ready, 1 );
                }

                // Mozilla, Opera and webkit nightlies currently support this event
                if ( document.addEventListener ) {
                    // Use the handy event callback
                    document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
                    // A fallback to window.onload, that will always work
                    window.addEventListener( "load", ReadyObj.ready, false );

                // If IE event model is used
                } else if ( document.attachEvent ) {
                    // ensure firing before onload,
                    // maybe late but safe also for iframes
                    document.attachEvent( "onreadystatechange", DOMContentLoaded );

                    // A fallback to window.onload, that will always work
                    window.attachEvent( "onload", ReadyObj.ready );

                    // If IE and not a frame
                    // continually check to see if the document is ready
                    var toplevel = false;

                    try {
                        toplevel = window.frameElement == null;
                    } catch(e) {}

                    if ( document.documentElement.doScroll && toplevel ) {
                        doScrollCheck();
                    }
                }
            },
            _Deferred: function() {
                var // callbacks list
                    callbacks = [],
                    // stored [ context , args ]
                    fired,
                    // to avoid firing when already doing so
                    firing,
                    // flag to know if the deferred has been cancelled
                    cancelled,
                    // the deferred itself
                    deferred  = {

                        // done( f1, f2, ...)
                        done: function() {
                            if ( !cancelled ) {
                                var args = arguments,
                                    i,
                                    length,
                                    elem,
                                    type,
                                    _fired;
                                if ( fired ) {
                                    _fired = fired;
                                    fired = 0;
                                }
                                for ( i = 0, length = args.length; i < length; i++ ) {
                                    elem = args[ i ];
                                    type = ReadyObj.type( elem );
                                    if ( type === "array" ) {
                                        deferred.done.apply( deferred, elem );
                                    } else if ( type === "function" ) {
                                        callbacks.push( elem );
                                    }
                                }
                                if ( _fired ) {
                                    deferred.resolveWith( _fired[ 0 ], _fired[ 1 ] );
                                }
                            }
                            return this;
                        },

                        // resolve with given context and args
                        resolveWith: function( context, args ) {
                            if ( !cancelled && !fired && !firing ) {
                                // make sure args are available (#8421)
                                args = args || [];
                                firing = 1;
                                try {
                                    while( callbacks[ 0 ] ) {
                                        callbacks.shift().apply( context, args );//shifts a callback, and applies it to document
                                    }
                                }
                                finally {
                                    fired = [ context, args ];
                                    firing = 0;
                                }
                            }
                            return this;
                        },

                        // resolve with this as context and given arguments
                        resolve: function() {
                            deferred.resolveWith( this, arguments );
                            return this;
                        },

                        // Has this deferred been resolved?
                        isResolved: function() {
                            return !!( firing || fired );
                        },

                        // Cancel
                        cancel: function() {
                            cancelled = 1;
                            callbacks = [];
                            return this;
                        }
                    };

                return deferred;
            },
            type: function( obj ) {
                return obj == null ?
                    String( obj ) :
                    class2type[ Object.prototype.toString.call(obj) ] || "object";
            }
        }
        // The DOM ready check for Internet Explorer
        function doScrollCheck() {
            if ( ReadyObj.isReady ) {
                return;
            }

            try {
                // If IE is used, use the trick by Diego Perini
                // http://javascript.nwbox.com/IEContentLoaded/
                document.documentElement.doScroll("left");
            } catch(e) {
                setTimeout( doScrollCheck, 1 );
                return;
            }

            // and execute any waiting functions
            ReadyObj.ready();
        }
        // Cleanup functions for the document ready method
        if ( document.addEventListener ) {
            DOMContentLoaded = function() {
                document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
                ReadyObj.ready();
            };

        } else if ( document.attachEvent ) {
            DOMContentLoaded = function() {
                // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
                if ( document.readyState === "complete" ) {
                    document.detachEvent( "onreadystatechange", DOMContentLoaded );
                    ReadyObj.ready();
                }
            };
        }
        function ready( fn ) {
            // Attach the listeners
            ReadyObj.bindReady();

            var type = ReadyObj.type( fn );

            // Add the callback
            readyList.done( fn );//readyList is result of _Deferred()
        }
        return ready;
        })();

Then, you can use it like:

然后,您可以使用它:

    ready(function(){
      $("body").floatingShare(); // Assuming jQuery Lib has been included as well
    });

By far, I think option 1 should be more acceptable.

到目前为止,我认为选项1应该更容易接受。

#3


4  

In your code there is a code sequence issue. According to jQuery code Sequence, You have to include jQuery first in your document and then all your custom function as suggested by @Bhushan Kawadkar in above answer.

在您的代码中存在代码序列问题。根据jQuery代码序列,你必须首先在你的文档中包含jQuery,然后在@Bhushan Kawadkar的建议中包含所有自定义函数。

If you still want to add your function in body where you have added it then you can include jQuery in <head> of document e.g

如果您仍想在添加它的正文中添加您的函数,那么您可以在文档的中包含jQuery,例如

<html>
 <head>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
  <script src="http://www.jqueryscript.net/demo/jQuery-Plugin-For-Horizontal-Floating-Social-Share-Bar/js/jquery.floating-share.js" type="text/javascript"></script>
</head>
<body>
 <div class="container"> 
  <script type="text/javascript">
$(function(){
$("body").floatingShare();
});
</script> 
</div>
</body>

And You plugin will start working.

而你的插件将开始工作。

Somehow it is recommended to add scripts(js) in footer to improve render times of your page.

不知何故,建议在页脚中添加脚本(js)以改善页面的渲染时间。

Here is a live demo for you.

这是一个现场演示。

http://codepen.io/anon/pen/AIEnl