如何使用纯javascript在任何网站中动态包含jQuery

如何使用纯javascript在任何网站中动态包含jQuery,javascript,jquery,Javascript,Jquery,我试图动态地包含jquery,我使用了以下代码- index.php <!doctype html> <html> <head> <script type="text/javascript" src="includejquery.js"></script> </head> <body> <div id="testing"></div> <script type="text/

我试图动态地包含jquery,我使用了以下代码-

index.php

<!doctype html>
<html>
<head>
    <script type="text/javascript" src="includejquery.js"></script>
</head>
<body>
<div id="testing"></div>

<script type="text/javascript">
    $(document).ready(function(){
        $('#testing').html('<p>This is a paragraph!</p>');
    });
</script>
</body>
</html>

但是jquery功能不起作用,它没有打印段落标记:-(请帮助我。请提前感谢。由于脚本加载异步,ready将不会启动


这应该是在页面上运行并阻止所有其他脚本以按时加载依赖项的第一件事。

这不起作用,因为您的
$(文档).ready(…
行在jQuery加载之前运行,因此它失败,因为
$
未定义(抛出
引用错误
)或者它指的不是jQuery。另外,您在加载jQuery之前调用了
jQuery.noConflict()
,如果该调用起作用,则意味着
$
根本不再引用jQuery,因此
$(文档)。ready(…
仍然不起作用

在任何现代浏览器中,您都可以在要添加的
script
元素上使用
load
事件,该事件告诉您脚本已加载。可能最好将回调传递到对
includejquery.js
的调用中,如下所示:

<!doctype html>
<html>
<head>
    <script type="text/javascript" src="includejquery.js"></script>
</head>
<body>
<div id="testing"></div>

<script type="text/javascript">
    includejQuery(function($){
        $('#testing').html('<p>This is a paragraph!</p>');
    });
</script>
</body>
</html>
这方面的变化:

  • includejquery.js
    中,只需定义一个函数并等待调用

  • 让该函数接受回调

  • 让它等待脚本加载

  • 加载脚本时,调用
    jQuery.noConflict
    ,如果有回调,则调用它并传入
    jQuery
    函数

  • 在HTML中,我调用该函数,并接收它作为
    $
    传递给我的参数,因此仅在该函数内
    $==jQuery
    ,即使在它之外,它也不会(因为
    noConflict


  • 从应用程序的实现有什么问题

    
    window.jQuery | | document.write(“”)
    
    附加到正文:

    function loadScript() {
       var script= document.createElement('script');
       script.type= 'text/javascript';
       script.src= 'http://www.mydomain/myscript.js';
       script.async = true;
       document.body.appendChild(script);
    }
    
    附在头上:

    function loadScript() {
       var head= document.getElementsByTagName('head')[0];
       var script= document.createElement('script');
       script.type= 'text/javascript';
       script.src= 'http://www.mydomain/myscript.js';
       script.async = true;
       head.appendChild(script);
    }
    

    通常,当您包含一些脚本时,浏览器会一步一步地同步加载它们

    但是如果你

    script.async = true;
    

    脚本将异步加载,其他脚本将不等待加载。若要解决此问题,可以删除此选项。

    脚本上存在onload事件。请使用该选项

      <!doctype html>
        <html>
        <head>
            <script type="text/javascript">
                window.onload = function() {
                    var script = document.createElement('script');
                    script.type = "text/javascript";
                    script.src = "http://code.jquery.com/jquery-2.1.1.min.js";
                    document.getElementsByTagName('head')[0].appendChild(script);
    
                    script.onload = function() {
                        $('#testing').html('<p>This is a paragraph!</p>');
                    }; 
    
                }; 
            </script>
        </head>
        <body>
        <div id="testing"></div>
    
        </body>
        </html>
    
    
    window.onload=函数(){
    var script=document.createElement('script');
    script.type=“text/javascript”;
    script.src=”http://code.jquery.com/jquery-2.1.1.min.js";
    document.getElementsByTagName('head')[0].appendChild(脚本);
    script.onload=函数(){
    $(“#testing”).html(“这是一个段落!

    ”); }; };
    检查您的浏览器js控制台。您可能会看到类似于
    $未定义且不是函数的内容。这是因为您正在中运行代码

    您可以尝试包装要在脚本标记事件中运行的jquery代码。也可以使用。

    有一个运行演示(单击“使用JS运行”)

    
    如果(!window.jQuery)
    {document.write(“”)}
    $(文档).ready(函数(){
    $('body').html('这是一个段落!

    '); });
    脚本的顺序很重要。

    替代解决方案

    (function () {
    
            initScript().then(function (v) {
                console.info(v);
                var script = document.getElementById("__jquery");
                script.onload = function () {
                    $(document).ready(function () {
                        // Main logic goes here.
                        $("body").css("background-color","gray");
                    });
                };
            });
    
            function initScript() {
                promise = new Promise(function(resolve,reject) {
                    try {
                        if(typeof jQuery == 'undefined') {
                            console.warn("jQuery doesn't exists");
                            var jQuery_script = document.createElement("script");
                            jQuery_script.src = "https://code.jquery.com/jquery-2.2.4.min.js";
                            jQuery_script.type = 'text/javascript';
                            jQuery_script.id = "__jquery";
                            document.head.appendChild(jQuery_script);
                            resolve("jQuery added succesfully.");
                        }
                        resolve("jQuery exists.")
                    } catch (ex) {
                        reject("Something went wrong on initScript() : ", ex);
                    }
                });
                return promise;
            }
    
        })();
    
    我使用promise是因为如果页面中没有jQuery,我们需要先等待加载它

    script.async = true;
    
      <!doctype html>
        <html>
        <head>
            <script type="text/javascript">
                window.onload = function() {
                    var script = document.createElement('script');
                    script.type = "text/javascript";
                    script.src = "http://code.jquery.com/jquery-2.1.1.min.js";
                    document.getElementsByTagName('head')[0].appendChild(script);
    
                    script.onload = function() {
                        $('#testing').html('<p>This is a paragraph!</p>');
                    }; 
    
                }; 
            </script>
        </head>
        <body>
        <div id="testing"></div>
    
        </body>
        </html>
    
    <script>
    if(!window.jQuery)
    {document.write('<script src=http://code.jquery.com/jquery-2.1.1.min.js><\/script>')}
    </script>
    
    <script>
    $(document).ready(function(){
        $('body').html('<p>This is a paragraph!</p>');
    });
    </script>
    
    (function () {
    
            initScript().then(function (v) {
                console.info(v);
                var script = document.getElementById("__jquery");
                script.onload = function () {
                    $(document).ready(function () {
                        // Main logic goes here.
                        $("body").css("background-color","gray");
                    });
                };
            });
    
            function initScript() {
                promise = new Promise(function(resolve,reject) {
                    try {
                        if(typeof jQuery == 'undefined') {
                            console.warn("jQuery doesn't exists");
                            var jQuery_script = document.createElement("script");
                            jQuery_script.src = "https://code.jquery.com/jquery-2.2.4.min.js";
                            jQuery_script.type = 'text/javascript';
                            jQuery_script.id = "__jquery";
                            document.head.appendChild(jQuery_script);
                            resolve("jQuery added succesfully.");
                        }
                        resolve("jQuery exists.")
                    } catch (ex) {
                        reject("Something went wrong on initScript() : ", ex);
                    }
                });
                return promise;
            }
    
        })();