This article mainly introduces the method of loading javascript files asynchronously and securely. The example analyzes the specific skills of javascript to implement asynchronous file loading, which has some reference value, for more information about how to asynchronously and securely load javascript files, see the example in this article. Share it with you for your reference. The details are as follows:
Usage:
(function() { __safeLoadScript("http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js?7.1.2", function() { alert(jQuery); });})();
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); });};
I hope this article will help you design javascript programs.