Home > Web Front-end > JS Tutorial > How to safely load javascript files asynchronously_javascript tips

How to safely load javascript files asynchronously_javascript tips

WBOY
Release: 2016-05-16 15:49:30
Original
1114 people have browsed it

The example in this article describes the method of asynchronously and safely loading javascript files. Share it with everyone for your reference. The details are as follows:

How to use:

(function() {
  __safeLoadScript("http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js", function() {
    alert(jQuery);
  });
})();

Copy after login

JavaScript implementation code:

window.__safeLoadScript = function(src, callback) {
  function addEvent(obj, type, fn) {
    if (obj.attachEvent) {
      obj['e' + type + fn] = fn;
      obj[type + fn] = function() { obj['e' + type + fn](window.event); }
      obj.attachEvent('on' + type, obj[type + fn]);
    } else
      obj.addEventListener(type, fn, false);
  }
  function async_load(src, callback) {
    var s = document.createElement('script');
    s.type = 'text/javascript';
    s.async = true;
    var protocol = (("https:" == document.location.protocol) ? "https://" : "http://");
    s.src = protocol + src;
    var x = document.getElementsByTagName('script')[0];
    x.parentNode.insertBefore(s, x);
    s.onload = s.onreadystatechange = function() {
      if(callback && (!this.readyState || this.readyState == "loaded" || this.readyState == "complete")) {
        callback();
      }
    };
  }
  addEvent(window, "load", function() { 
    async_load(src, callback);
  });
};

Copy after login

I hope this article will be helpful to everyone’s JavaScript programming design.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template