【问题标题】:How to execute JS file only when user click [duplicate]仅当用户单击 [重复] 时如何执行 JS 文件
【发布时间】:2021-04-22 12:06:03
【问题描述】:

Google Places javascript 文件位于我的页脚中(如下所示)。 我试图在用户单击页面之前不加载此 JS 文件,或者更好地单击特定的 div (class= .searchbox2)。基本上,在用户点击页面之前不要加载 Google JS。 谢谢!

<script async defer src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=false&libraries=places&region=AU&language=en&key=xxxxxxxxxx"></script> 

【问题讨论】:

    标签: javascript


    【解决方案1】:

    对于这样的事情,我推荐Filament Group 的loadJS。您可以按如下方式使用它:

    // assuming loadJS is included on the page
    
    const searchBox = document.querySelector('.searchbox2');
    const mapsApi = 'https://maps.googleapis.com/maps/api/js' +
      '?v=3.exp&signed_in=false&libraries=places' + 
      '&region=AU&language=en&key=xxxxxxxxxx';
    
    searchBox.addEventListener('click', function () {
      loadJS(mapsApi, function () {
        // any code here will run once the Maps API script has loaded
      });
    });
    
    

    【讨论】:

    • 您能详细说明一下吗?
    • 不需要添加库以将脚本附加到 DOM。
    • @wuerfelfreak 我添加了一个示例。 :-) @sbolel 我不会将 loadJS 归类为库而是函数。
    • 上面的代码试过了,还是不行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-25
    • 2021-12-12
    • 1970-01-01
    • 1970-01-01
    • 2021-04-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多