避免两次请求相同的外部脚本

时间:2020-11-10 15:06:51

标签: javascript jquery

我通过将其添加到HTML文件中来请求外部脚本:

<script>
  $(document).on("turbolinks:load", function() {
    $.getScript("https://example.com/script");
  });
</script>

说脚本的内容如下:

doSomething = function() {
  // ...
};

我的网站是一个带Turbolinks的Ruby on Rails应用,可在两次页面访问之间缓存所请求脚本的内容。我的脚本标签对此一无所知,因此,如果我重新访问该页面,它将再次请求该脚本。如何避免这种情况?我当前的解决方案是检查脚本内容是否已知:

<script>
  $(document).on("turbolinks:load", function() {
    if (!window.doSomething) {
      $.getScript("https://example.com/script");
    }
  });
</script>

但这取决于脚本中的内容是否保持不变。因此,我宁愿检查源https://example.com/script中的脚本是否已经存在?也许还有其他方法。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

就像epascarello一样,$。getScript会追加到头部,因此在获取它之前请确保它不在头部。

if (!$('head script[src^="https://example.com/script"]').length){
    $.getScript("https://example.com/script");
}

使用Attribute Starts With Selector是因为$ .getScript附加了时间戳,以避免获取已经缓存的版本,即每次都请求一个新的URL。

如果要多次使用它:

function getScriptOnce(url){
    let selector = 'head script[src^="' + url + '"]'; 
    if (!$(selector).length){
        $.getScript(url);
    }
}

getScriptOnce("https://example.com/script");