在事件上加载脚本并触发相同的事件

时间:2016-07-11 17:09:50

标签: javascript asynchronous lazy-loading

我正在尝试在某个事件上添加某些javascript文件,比如点击。我试图使用Javascript在同一事件上使用,只有它被触发。这是因为脚本减慢了页面加载速度,否则就不需要脚本了。

我可以将脚本移动到页脚并进行全部设置,或者通过仅在需要时通过事件触发来加载它们来以编程方式执行此操作吗?以下是我到目前为止:

HTML:

<a id="customId" href="#myLink"></a>

使用Javascript:

$(document).ready(function() {
    //The async addition
    var myJS = {
      lazyload : function(scriptSrc) {
            if(!this.isPresent(scriptSrc)){
                var scriptTag = document.createElement('script'); 
                scriptTag.src =  scriptSrc;
                scriptTag.async = true; 
                document.getElementsByTagName('head')[0].appendChild(scriptTag);
             }
            return false; 
        }
    }; 

    //The event trigger needs to do something using the said script 
    if($('#customId')){
        //Approach 1: 
        var mapEl = document.getElementById("customId"); 
        mapEl.addEventListener("click", customEventHandler, false);
        //mapEl.dispatchEvent(event);
              //*where
              customEventHandler : function(e){
                  e.preventDefault; 
                  myJS.lazyload('/jsfile.js'); 
                // Update or use link relative #href (not complete path) and use the javascript without navigating out of page.
                  //e.currentTarget.dispatchEvent(?); 
            }     

        //2nd attempt: Adds the script, but not able to trigger event to use JS 
        $('#customId').click(function(event) {
          event.preventDefault(); 
          myJS.lazyload('/jsfile.js'); 
        //Either approach: 
        //Trigger the custom event to do an actual click after doing the lazy load, using the JS file
(click);    $('#customId').trigger('click'); //Is this correct on same element ID

      });

   }

}

1 个答案:

答案 0 :(得分:0)

尝试使用onload元素script事件,定义自定义事件以防止在元素上递归调用本机click事件处理程序

$(document).ready(function() {
  //The async addition
  var myJS = {
    lazyload: function(scriptSrc, id, type) {
      // use `.is()` to check if `script` element has `src` 
      // equal to `scriptSrc`
      if (!$("script[src='"+ scriptSrc  +"']").is("*")) {
        var scriptTag = document.createElement("script");
        scriptTag.src = scriptSrc;
        scriptTag.async = true;
        // use `script` `onload` to trigger custom event `customClick`
        scriptTag.onload = function() {
          $(id).trigger(type)
        };
        document.getElementsByTagName("head")[0].appendChild(scriptTag);
      }
      return false;
    }
  };

  $("#customId").on("click", function() {
    myJS.lazyload("jsfile.js", "#" + this.id, "customClick");
  })
  // do stuff at `customClick` event
  .one("customClick", function(e) {
    customClick(e.type)
  });

});

plnkr http://plnkr.co/edit/Rw4BRAfSYlXXe5c6IUml?p=preview