javascript - adding two script tags (in body) before continue another code from same js file
如何修改下面的代码?在从函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | var loadJS = function(url, implementationCode){//url, url_Next //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');//will add scriptTag_Next scriptTag.type = 'text/javascript'; scriptTag.setAttribute('nonce','22os9h3sdfa'); scriptTag.src = url; scriptTag.onload = implementationCode;//Will It be work? -> scriptTag.onload = scriptTag_Next = implementationCode; scriptTag.onreadystatechange = implementationCode;//like as above scriptTag_Next.onreadystatechange ?? document.body.appendChild(scriptTag); }; var yourCodeToBeCalled = function(){ console.log('okay'); } loadJS('js/jquery-3_1_1.min.js', yourCodeToBeCalled);//My my suggestion loadJS('js/jquery-3_1_1.min.js', 'js/test.js' yourCodeToBeCalled) |
我借用的原始代码:link
好的,我找到了一种逐个执行脚本的方法。由于加载脚本的顺序不正确,不再有错误,例如:当下一个脚本使用jQuery命令时,缺少jQuery框架。所以我决定用承诺来解决这个问题。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | var loadJS = function(url) { /*url is URL of external file*/ return new Promise(function(resolve, reject) { var scriptTag = document.createElement('script'); scriptTag.type = 'text/javascript'; scriptTag.setAttribute('nonce', '22os9h3sdfa'); scriptTag.onload = resolve; scriptTag.onerror = reject; scriptTag.src = url; document.body.appendChild(scriptTag); }); }; loadJS('js/jquery-3_1_1.min.js').then(() => { return loadJS('js/library.js'); }).then(() => { var $ = jQuery.noConflict();//jQuery.noConflict(); }); |
现在'jquery-3_1_1.min.js'在'library.js'等后面执行。
问候语!
假设我正确理解您的需求,
1 2 3 4 5 6 7 8 | (function() { var head = document.getElementsByTagName('head') loadJS('somescript.js', function() { console.log('on load') }, head) loadJS('somescript2.js', function() { console.log('on load2') }, head) // This is your code to execute once the scripts have loaded. console.log('Okay'); })(); |
另外,您还需要从
编辑:根据您最近的更改,您可以省略中间的参数(回调),这是不需要的。
编辑:考虑到您的最新更改,此代码应该有效:
1 2 3 4 5 6 7 | (function() { loadJS('somescript.js') loadJS('somescript2.js') // This is your code to execute once the scripts have loaded. console.log('Okay'); })(); |
现在在loadJS中有了
我不知道为什么要将script元素添加到
1 | location.appendChild(scriptTag); |
你可能想试试
1 | document.body.appendChild(scriptTag); |