简体   繁体   English

用户单击元素时加载第三方JavaScript

[英]Load 3rd Party JavaScript when user clicks an element

I know I can inject the script when the user clicks an element by creating a script element and injecting it on the page via document.appendChild. 我知道当用户单击一个元素时,可以通过创建脚本元素并将其通过document.appendChild注入页面上来注入脚本。 However, the script is listening for onload and onDOMContentReady (or their own home grown domReady event, not sure). 但是,脚本正在侦听onload和onDOMContentReady(或不确定它们自己的本地生成的domReady事件)。

If I inject the script only when the user clicks an element, the callbacks for onload/onDOMContentReady will never fire because those events have already passed. 如果仅在用户单击元素时才注入脚本,则onload / onDOMContentReady的回调将永远不会触发,因为这些事件已经通过。

Any ideas? 有任何想法吗? This 3rd party script pulls in all these other requests and it's not optimal for page loading. 此第三方脚本会提取所有其他请求,因此并非页面加载的最佳选择。

EDIT: I read the question again...and if you are using something like jQuery, it will fire your handler function in any other document ready calls even if document ready has already been fired. 编辑:我再次阅读了问题...如果您使用的是jQuery之类的东西,即使已经准备好文档就绪,它也会在其他任何文档就绪调用中触发您的处理程序函数。 It will just execute the function right away. 它将立即执行该功能。 If you are looking for a pure javascript way to do it, you need to take extra consideration to check to see if dom ready has already been fired, and fire your function yourself, otherwise attach it to the dom ready callback. 如果您正在寻找一种纯JavaScript的方式来执行此操作,则需要多加考虑以检查是否已触发dom ready,并自行触发函数,否则将其附加到dom ready回调中。

I don't see a problem with just doing something like this (with jquery for brevity): 我只做这样的事情就没有问题(为简洁起见,使用jQuery):

// on document ready
$( function() {

    // attach the click handler
    $('#loadScript').click( function( e ) {

        // on click, get the script
        $.getScript('path/to/your/script.js', function() {

            // your script is loaded, so what you need from here
            // to handle this click event.
        });
    });
});

I think you are over thinking it a bit. 我想您有点想不通了。 You only need to worry about making it possible to load the script once the dom elements are ready. 您只需要担心一旦dom元素准备好就可以加载脚本。 You could look at using something like require.js as well. 您也可以考虑使用require.js之类的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM