Dynamically load JS inside JS
我有一个动态网页,需要在另一个javascript文件中导入一个外部JS文件(在
我试图寻找一个可行的解决方案,但没有奏效。
我尝试使用
jquery中的解决方案也很好
我的猜测是,在您的DOM唯一解决方案中,您执行了如下操作:
1 2 3 | var script = document.createElement('script'); script.src = something; //do stuff with the script |
首先,这不起作用,因为脚本没有添加到文档树中,所以不会被加载。此外,即使这样做了,也会在加载另一个脚本时继续执行JavaScript,因此在该脚本完全加载之前,它的内容将不可用。
您可以聆听脚本的
1 2 3 4 5 6 7 | var script = document.createElement('script'); script.onload = function () { //do stuff with the script }; script.src = something; document.head.appendChild(script); //or something of the likes |
jquery的
1 2 3 4 5 6 7 8 | jQuery.loadScript = function (url, callback) { jQuery.ajax({ url: url, dataType: 'script', success: callback, async: true }); } |
使用方式如下:
1 2 3 | if (typeof someObject == 'undefined') $.loadScript('url_to_someScript.js', function(){ //Stuff to do after someScript has loaded }); |
我需要经常这样做,所以我使用这个:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | var loadJS = function(url, implementationCode, location){ //url is URL of external file, implementationCode is the code //to be called from the file, location is the location to //insert the element var scriptTag = document.createElement('script'); scriptTag.src = url; scriptTag.onload = implementationCode; scriptTag.onreadystatechange = implementationCode; location.appendChild(scriptTag); }; var yourCodeToBeCalled = function(){ //your code goes here } loadJS('yourcode.js', yourCodeToBeCalled, document.body); |
有关详细信息,请参阅此站点如何在另一个javascript文件中包含javascript文件?这就是我的函数思想的来源。
您可以在页面内动态加载JS,而不是另一个JS文件。
必须使用getscript加载JS文件
1 2 3 4 5 6 | $.getScript("ajax/test.js", function(data, textStatus, jqxhr) { console.log(data); //data returned console.log(textStatus); //success console.log(jqxhr.status); //200 console.log('Load was performed.'); }); |
亡灵术。
我使用它加载依赖脚本;
它与IE8+一起工作,而不添加任何对其他库(如jquery)的依赖!< BR>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 | var cScriptLoader = (function () { function cScriptLoader(files) { var _this = this; this.log = function (t) { console.log("ScriptLoader:" + t); }; this.withNoCache = function (filename) { if (filename.indexOf("?") === -1) filename +="?no_cache=" + new Date().getTime(); else filename +="&no_cache=" + new Date().getTime(); return filename; }; this.loadStyle = function (filename) { // HTMLLinkElement var link = document.createElement("link"); link.rel ="stylesheet"; link.type ="text/css"; link.href = _this.withNoCache(filename); _this.log('Loading style ' + filename); link.onload = function () { _this.log('Loaded style"' + filename + '".'); }; link.onerror = function () { _this.log('Error loading style"' + filename + '".'); }; _this.m_head.appendChild(link); }; this.loadScript = function (i) { var script = document.createElement('script'); script.type = 'text/javascript'; script.src = _this.withNoCache(_this.m_js_files[i]); var loadNextScript = function () { if (i + 1 < _this.m_js_files.length) { _this.loadScript(i + 1); } }; script.onload = function () { _this.log('Loaded script"' + _this.m_js_files[i] + '".'); loadNextScript(); }; script.onerror = function () { _this.log('Error loading script"' + _this.m_js_files[i] + '".'); loadNextScript(); }; _this.log('Loading script"' + _this.m_js_files[i] + '".'); _this.m_head.appendChild(script); }; this.loadFiles = function () { // this.log(this.m_css_files); // this.log(this.m_js_files); for (var i = 0; i < _this.m_css_files.length; ++i) _this.loadStyle(_this.m_css_files[i]); _this.loadScript(0); }; this.m_js_files = []; this.m_css_files = []; this.m_head = document.getElementsByTagName("head")[0]; // this.m_head = document.head; // IE9+ only function endsWith(str, suffix) { if (str === null || suffix === null) return false; return str.indexOf(suffix, str.length - suffix.length) !== -1; } for (var i = 0; i < files.length; ++i) { if (endsWith(files[i],".css")) { this.m_css_files.push(files[i]); } else if (endsWith(files[i],".js")) { this.m_js_files.push(files[i]); } else this.log('Error unknown filetype"' + files[i] + '".'); } } return cScriptLoader; })(); var ScriptLoader = new cScriptLoader(["foo.css","Scripts/Script4.js","foobar.css","Scripts/Script1.js","Scripts/Script2.js","Scripts/Script3.js"]); ScriptLoader.loadFiles(); |
如果您对用于创建此内容的typescript版本感兴趣:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 | class cScriptLoader { private m_js_files: string[]; private m_css_files: string[]; private m_head:HTMLHeadElement; private log = (t:any) => { console.log("ScriptLoader:" + t); } constructor(files: string[]) { this.m_js_files = []; this.m_css_files = []; this.m_head = document.getElementsByTagName("head")[0]; // this.m_head = document.head; // IE9+ only function endsWith(str:string, suffix:string):boolean { if(str === null || suffix === null) return false; return str.indexOf(suffix, str.length - suffix.length) !== -1; } for(var i:number = 0; i < files.length; ++i) { if(endsWith(files[i],".css")) { this.m_css_files.push(files[i]); } else if(endsWith(files[i],".js")) { this.m_js_files.push(files[i]); } else this.log('Error unknown filetype"' + files[i] +'".'); } } public withNoCache = (filename:string):string => { if(filename.indexOf("?") === -1) filename +="?no_cache=" + new Date().getTime(); else filename +="&no_cache=" + new Date().getTime(); return filename; } public loadStyle = (filename:string) => { // HTMLLinkElement var link = document.createElement("link"); link.rel ="stylesheet"; link.type ="text/css"; link.href = this.withNoCache(filename); this.log('Loading style ' + filename); link.onload = () => { this.log('Loaded style"' + filename + '".'); }; link.onerror = () => { this.log('Error loading style"' + filename + '".'); }; this.m_head.appendChild(link); } public loadScript = (i:number) => { var script = document.createElement('script'); script.type = 'text/javascript'; script.src = this.withNoCache(this.m_js_files[i]); var loadNextScript = () => { if (i + 1 < this.m_js_files.length) { this.loadScript(i + 1); } } script.onload = () => { this.log('Loaded script"' + this.m_js_files[i] + '".'); loadNextScript(); }; script.onerror = () => { this.log('Error loading script"' + this.m_js_files[i] + '".'); loadNextScript(); }; this.log('Loading script"' + this.m_js_files[i] + '".'); this.m_head.appendChild(script); } public loadFiles = () => { // this.log(this.m_css_files); // this.log(this.m_js_files); for(var i:number = 0; i < this.m_css_files.length; ++i) this.loadStyle(this.m_css_files[i]) this.loadScript(0); } } var ScriptLoader = new cScriptLoader(["foo.css","Scripts/Script4.js","foobar.css","Scripts/Script1.js","Scripts/Script2.js","Scripts/Script3.js"]); ScriptLoader.loadFiles(); |
如果要加载脚本的动态列表,请将脚本写入一个属性,例如data main。
做一个EDOCX1[10]
如
1 2 3 4 5 6 7 8 9 10 | var target = document.currentScript || (function() { var scripts = document.getElementsByTagName('script'); // Note: this is for IE as IE doesn't support currentScript // this does not work if you have deferred loading with async // e.g. <script src="..." async="async"> // https://web.archive.org/web/20180618155601/https://www.w3schools.com/TAgs/att_script_async.asp return scripts[scripts.length - 1]; })(); target.getAttribute("data-main").split(',') |
获取列表。
如果您希望脚本是可访问的,那么可以使用RequireJS,或者按照jQuery的示例来扩展与下面类似的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | jQuery.cachedScript = function( url, options ) { // Allow user to set any option except for dataType, cache, and url options = $.extend( options || {}, { dataType:"script", cache: true, url: url }); // Use $.ajax() since it is more flexible than $.getScript // Return the jqXHR object so we can chain callbacks return jQuery.ajax( options ); }; // Usage $.cachedScript("ajax/test.js" ).done(function( script, textStatus ) { console.log( textStatus ); }); |
参考:jquery.getscript()jquery api文档
我建议在AMD JavaScript类文件中使用RequireJS
如何在这里使用它的好例子
Understanding RequireJS for Effective JavaScript Module Loading
您可以使用jquery:
1 2 3 4 5 6 | $.getScript("ajax/test.js", function(data, textStatus, jqxhr) { console.log(data); //data returned console.log(textStatus); //success console.log(jqxhr.status); //200 console.log('Load was performed.'); }); |
此链接应该有助于:http://api.jquery.com/jquery.getscript/
为了编写插件,我需要在JS文件中加载外部脚本和样式,所有这些都是预定义的。为此,我做了以下工作:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | this.loadRequiredFiles = function (callback) { var scripts = ['xx.js', 'yy.js']; var styles = ['zz.css']; var filesloaded = 0; var filestoload = scripts.length + styles.length; for (var i = 0; i < scripts.length; i++) { log('Loading script ' + scripts[i]); var script = document.createElement('script'); script.type = 'text/javascript'; script.src = scripts[i]; script.onload = function () { log('Loaded script'); log(this); filesloaded++; // (This means increment, i.e. add one) finishLoad(); }; document.head.appendChild(script); } for (var i = 0; i < styles.length; i++) { log('Loading style ' + styles[i]); var style = document.createElement('link'); style.rel = 'stylesheet'; style.href = styles[i]; style.type = 'text/css'; style.onload = function () { log('Loaded style'); log(this); filesloaded++; finishLoad(); }; document.head.appendChild(style); } function finishLoad() { if (filesloaded === filestoload) { callback(); } } }; |
上下文中的更多脚本:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 | function myPlugin() { var opts = { verbose: false }; ///< The options required to run this function var self = this; ///< An alias to 'this' in case we're in jQuery ///< Constants required for this function to work this.getOptions = function() { return opts; }; this.setOptions = function(options) { for (var x in options) { opts[x] = options[x]; } }; /** * @brief Load the required files for this plugin * @param {Function} callback A callback function to run when all files have been loaded */ this.loadRequiredFiles = function (callback) { var scripts = ['xx.js', 'yy.js']; var styles = ['zz.css']; var filesloaded = 0; var filestoload = scripts.length + styles.length; for (var i = 0; i < scripts.length; i++) { log('Loading script ' + scripts[i]); var script = document.createElement('script'); script.type = 'text/javascript'; script.src = scripts[i]; script.onload = function () { log('Loaded script'); log(this); filesloaded++; finishLoad(); }; document.head.appendChild(script); } for (var i = 0; i < styles.length; i++) { log('Loading style ' + styles[i]); var style = document.createElement('link'); style.rel = 'stylesheet'; style.href = styles[i]; style.type = 'text/css'; style.onload = function () { log('Loaded style'); log(this); filesloaded++; finishLoad(); }; document.head.appendChild(style); } function finishLoad() { if (filesloaded === filestoload) { callback(); } } }; /** * @brief Enable user-controlled logging within this function * @param {String} msg The message to log * @param {Boolean} force True to log message even if user has set logging to false */ function log(msg, force) { if (opts.verbose || force) { console.log(msg); } } /** * @brief Initialise this function */ this.init = function() { self.loadRequiredFiles(self.afterLoadRequiredFiles); }; this.afterLoadRequiredFiles = function () { // Do stuff }; } |
jquery有
Description: Load a JavaScript file from the server using a GET HTTP request, then execute it.
如果有许多具有依赖性的文件,请使用amd/requirejs。http://requirejs.org网站/
下面是一些动态加载javascript和css文件的lib:
https://github.com/todotresde/javascript-loader
我想按顺序和动态地加载CSS和JS文件是有用的。
支持扩展以加载所需的任何lib,而不仅仅是主文件,您可以使用它来加载自定义文件。
即。:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | <html> <head> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> <script src="scripts/javascript-loader.js" type="text/javascript" charset="utf-8"> <script type="text/javascript"> $(function() { registerLib("threejs", test); function test(){ console.log(THREE); } registerLib("tinymce", draw); function draw(){ tinymce.init({selector:'textarea'}); } }); </head> <body> <textarea>Your content here.</textarea> </body> |
您可以使用jquery的