【问题标题】:External css and jquery in external js file外部 js 文件中的外部 css 和 jquery
【发布时间】:2016-01-11 14:32:57
【问题描述】:

如何在外部 .js 文件中包含 jquery libray src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"?另外如何在 .js 文件中包含 .css 文件?

【问题讨论】:

  • 嗨 Jaideep,这个问题似乎不清楚。您能否发布到目前为止您已经尝试过的/或您正在尝试实现的示例?
  • 我只想在 javascript 文件中包含 jquery lib,因为我想用 javascript 编写 jquery 代码。我还想将外部 css 应用于我在 javascript 文件中创建的 div
  • 去看看这个帖子你会找到答案stackoverflow.com/questions/18261214/…
  • 如何将外部css应用于javascript文件中创建的div?

标签: javascript jquery css


【解决方案1】:
var x = document.createElement('script');
x.src = 'http://example.com/test.js';
document.getElementsByTagName("head")[0].appendChild(x);

【讨论】:

  • 最后一行的“head”是什么?为什么需要 appendChild?
  • head 在你的 html 中引用 标签。它通常应该在你的 标签之前,它是人们通常在 html 中加载脚本文件的地方
【解决方案2】:

您只能在 HTML 文件中添加 JS 文件。当你运行一个 JS 应用程序打开一个网站时,你正在查看包含 JS 文件的 HTML 文件。

如果您使用的是 jQuery,您可以使用以下方法将 JS 文件添加到 HTML:

 $.getScript(url, successCallback);

这是一个异步 Vanilla JS 函数

function loadScript(src, callback)
{
  var s,
      r,
      t;
  r = false;
  s = document.createElement('script');
  s.type = 'text/javascript';
  s.src = src;
  s.onload = s.onreadystatechange = function() {
    //console.log( this.readyState ); //uncomment this line to see which ready states are called.
    if ( !r && (!this.readyState || this.readyState == 'complete') )
    {
      r = true;
      callback();
    }
  };
  t = document.getElementsByTagName('script')[0];
  t.parentNode.insertBefore(s, t);
}

或者只是将所有代码写在一个文件中,或者使用构建系统来合并和缩小文件以用于生产。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-07
    • 2018-04-27
    • 2013-10-22
    相关资源
    最近更新 更多