如何在JS文件中添加jQuery

127 javascript jquery

我有一些特定于排序表的代码.由于代码在大多数页面中很常见,我想制作一个JS文件,该文件将包含代码,所有使用它的页面都可以从那里引用它.

问题是:如何将jQuery和表分类器插件添加到该.js文件中?

我试过这样的事情:

document.writeln('<script src="/javascripts/jquery.js" type="text/javascript"></script>');
document.writeln('<script type="text/javascript" src="/javascripts/jquery.tablesorter.js"></script>');
Run Code Online (Sandbox Code Playgroud)

但这似乎行不通.

做这个的最好方式是什么?

Dan*_*ura 155

var script = document.createElement('script');
script.src = 'https://code.jquery.com/jquery-3.4.1.min.js';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);
Run Code Online (Sandbox Code Playgroud)

  • 我会用`//`替换`http://`作为相关协议.假设适用于src属性. (16认同)

小智 79

如果你想包含来自另一个JS文件的jQuery代码,这应该可以解决问题:

我的HTML文件中有以下内容:

<script src="jquery-1.6.1.js"></script>
<script src="my_jquery.js"></script>
Run Code Online (Sandbox Code Playgroud)

我创建了一个单独的my_jquery.js文件,其中包含以下内容:

$(document).ready(function() {
  $('a').click(function(event) {
    event.preventDefault();
    $(this).hide("slow");
  });
});
Run Code Online (Sandbox Code Playgroud)

  • 那么,它仍然是一个很好的答案,它可能会帮助其他人寻找如何做到这一点.欢迎来到stackoverflow,R-The_Master! (43认同)
  • @genesisφ这是目前"jquery包含js"的谷歌搜索结果,并且拥有13k的观看次数lol. (9认同)
  • 帮帮我...... 3年后:) (8认同)
  • 我只想指出:包含js文件的顺序很重要. (5认同)
  • 该死的直!当然帮助了我:P.真棒! (2认同)

Hee*_*lla 15

您可以使用以下代码在JS文件中实现加载jQuery.我还添加了一个正在运行的jQuery JSFiddle,它正在使用自调用函数.

// Anonymous "self-invoking" function
(function() {
    var startingTime = new Date().getTime();
    // Load the script
    var script = document.createElement("SCRIPT");
    script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js';
    script.type = 'text/javascript';
    document.getElementsByTagName("head")[0].appendChild(script);

    // Poll for jQuery to come into existance
    var checkReady = function(callback) {
        if (window.jQuery) {
            callback(jQuery);
        }
        else {
            window.setTimeout(function() { checkReady(callback); }, 20);
        }
    };

    // Start polling...
    checkReady(function($) {
        $(function() {
            var endingTime = new Date().getTime();
            var tookTime = endingTime - startingTime;
            window.alert("jQuery is loaded, after " + tookTime + " milliseconds!");
        });
    });
})();
Run Code Online (Sandbox Code Playgroud)

其他选项: - 您也可以尝试Require.JS,这是一个JS模块加载器.

  • 最佳答案,非常感谢! (2认同)

abl*_*aze 6

如果你想从你的项目中添加对任何js文件的引用,你也可以使用引用标记直接添加它,在Visual Studio IDE中,这可以通过将外部文件从解决方案资源管理器拖放到当前文件来自动处理(这适用于标记文件,.js和.css文件)

/// <reference path="jquery-2.0.3.js" />
Run Code Online (Sandbox Code Playgroud)


ofi*_*hai 6

/* Adding the script tag to the head as suggested before */

    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = "http://code.jquery.com/jquery-2.2.1.min.js";

    // Then bind the event to the callback function.
    // There are several events for cross browser compatibility.
    script.onreadystatechange = handler;
    script.onload = handler;

    // Fire the loading
    head.appendChild(script);

    function handler(){
       console.log('jquery added :)');
    }
Run Code Online (Sandbox Code Playgroud)


Sal*_*lty 5

问题是你在</script>脚本中使用,这是结束脚本标记.试试这个:

document.writeln('<script src="/javascripts/jquery.js" type="text/javascript"></sc'+'ript>');
document.writeln('<script type="text/javascript" src="/javascripts/jquery.tablesorter.js"></sc'+'ript>');
Run Code Online (Sandbox Code Playgroud)

  • 这个解决方案什么都不做,因为`script`标签已被视为一个字符串,而不是标记. (2认同)

Fai*_* Mq 5

这是我在其他一些论坛中采用的一些解决方案的解决方案.

这样,您可以在一个js文件中引用css文件和其他js文件,从而下次只在一个地方进行更改.如果您有任何疑虑,请告诉我.

我做了以下事情:

  1. 我创建了一个名为jQueryIncluder.js的js
  2. 声明并执行此文件中的代码

    function getVirtualDirectory() {
      var vDir = document.location.pathname.split('/');
      return '/' + vDir[1] + '/';
    }
    
    function include_jQueryFilesToPage() {
      var siteAddress = location.protocol + '//' + document.location.hostname + getVirtualDirectory(); 
      var jqCSSFilePath =  siteAddress + 'includes/jQueryCSS/ehrgreen-theme/jquery-ui-1.8.2.custom.css';
      var jqCoreFilePath = siteAddress + 'includes/jquery-1.4.1.min.js';
      var jqUIFilePath =   siteAddress + 'includes/jquery-ui-1.8.2.custom.min.js';
      var head  = document.getElementsByTagName('head')[0]; 
    
      // jQuery CSS jnclude
      var jqCSS = 'cssIDJQ';  // you could encode the css path itself to generate id.
      if (!document.getElementById(jqCSS)) { 
        var link  = document.createElement('link'); 
        link.id  = jqCSS; 
        link.rel  = 'stylesheet'; 
        link.type = 'text/css'; 
        link.href = jqCSSFilePath; 
        link.media = 'all'; 
        head.appendChild(link); 
      } 
    
      // Core jQuery include
      var jqc = "coreFileRefIDJQ";  
      if (!document.getElementById(jqc)) 
        document.write('<scr' + 'ipt type="text/javascript" id="' + jqc + '" src="' + jqCoreFilePath + '"></scr' + 'ipt>');
    
      // jQueryUI include
      var jqUI = "uiFileRefIDJQ";  
      if (!document.getElementById(jqUI)) 
        document.write('<scr' + 'ipt type="text/javascript" id="' + jqUI + '" src="' + jqUIFilePath + '"></scr' + 'ipt>');
    }
    
    include_jQueryFilesToPage();
    
    Run Code Online (Sandbox Code Playgroud)
  3. 我在我的.Net项目的另一个js或xsl文件中引用了上面的jQueryIncluder.js文件,如下所示:

    <script type="text/javascript" src="~/includes/jQueryIncluder.js"></script>
    
    Run Code Online (Sandbox Code Playgroud)

我希望我的努力得到赞赏.

谢谢


Ama*_*gar 5

无法在另一个js文件中导入js文件

在js中使用jquery的方法是

导入html或您正在使用的任何视图页面中的js,您将在其中包含js文件

view.html

 <script src="<%=request.getContextPath()%>/js/jquery-1.11.3.js"></script>
 <script src="<%=request.getContextPath()%>/js/default.js"></script>
Run Code Online (Sandbox Code Playgroud)

default.js

$('document').ready(function() {
    $('li#user').click(function() {
         $(this).addClass('selectedEmp');
    });
});
Run Code Online (Sandbox Code Playgroud)

这肯定会对你有用


top*_*pro 5

以下答案是另一位用户之前发布的,但没有提供任何解释,因此我决定注释正在发生的事情。

var jQueryScript = document.createElement('script');
jQueryScript.setAttribute('src','https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js');
document.head.appendChild(jQueryScript);
Run Code Online (Sandbox Code Playgroud)

解释

通过在 JavaScript 中创建一个 script 元素,然后将src属性设置为 jQuery 文件的路径,可以解决该问题。

var jQueryScript = document.createElement('script');
Run Code Online (Sandbox Code Playgroud)

上面我们创建了script元素。

接下来,我们将src属性设置为路径,如前所述。这可以设置为

https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js
Run Code Online (Sandbox Code Playgroud)

或者

/your/path/to/jquery/file
Run Code Online (Sandbox Code Playgroud)

正在使用:

jQueryScript.setAttribute('src','https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js');
Run Code Online (Sandbox Code Playgroud)

最后但并非最不重要的一点是将新元素附加到文档中head

document.head.appendChild(jQueryScript);
Run Code Online (Sandbox Code Playgroud)

或者body

document.body.appendChild(jQueryScript);
Run Code Online (Sandbox Code Playgroud)

正在使用

var jQueryScript = document.createElement('script');
jQueryScript.setAttribute('src','https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js');
document.head.appendChild(jQueryScript);
Run Code Online (Sandbox Code Playgroud)


Sin*_*our -3

为什么使用 Javascript 来编写脚本标签?只需将脚本标签添加到您的 head 部分即可。所以你的文档看起来像这样:

<html>
  <head>
    <!-- Whatever you want here -->
    <script src="/javascripts/jquery.js" type="text/javascript"></script>
    <script src="/javascripts/jquery.tablesorter.js" type="text/javascript"></script>
  </head>
  <body>
    The contents of the page.
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

  • 是的,他们可以,卡纳瓦尔。就浏览器而言,无论您是在 HTML 中还是在脚本本身中添加脚本标记并不重要,因为它对结果的解释是相同的。 (6认同)
  • 我说的是JS文件。如何将 jQuery 引用添加到 JS 文件 (2认同)