[英]Dynamically Loaded Script is undefined after load
When adding a script loaded dynamically, I can access main object during execution but once the page is loaded, if I try to access that from console, it throws undefined. 当添加动态加载的脚本时,我可以在执行期间访问主对象,但是一旦页面加载完毕,如果我尝试从控制台访问该对象,则会抛出未定义的对象。 For example,
例如,
var js, fjs = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js";
js.onload = ()=> { /* do something when script loads */}
fjs.parentNode.insertBefore(js, fjs);
This should ideally append FB object to window, and it does that during execution of page. 理想情况下,这应将FB对象附加到窗口,并在页面执行期间执行。 I can access
window.FB
while the aforesaid JS is executing, but once the page is loaded (and I know that js.onload is also executed), I can't access FB.someOperation. 我可以在执行上述JS的同时访问
window.FB
,但是一旦页面被加载(并且我知道js.onload也已执行),我就无法访问FB.someOperation。
What is the solution to ensure that dynamically added script is always available (even after page has loaded) 有什么解决方案可确保动态添加的脚本始终可用(即使在页面加载后)
Remember to double check the property names . 请记住仔细检查属性名称 。
onLoad
should be onload
(all lowercase). onLoad
应该是onload
(所有小写字母)。
var d = document; var id = 'hello'; var js, fjs = d.getElementsByTagName('script')[0]; js = d.createElement('script'); js.id = id; js.src = "//connect.facebook.net/en_US/all.js"; js.onload = () => { // ^--------------------------- note the lowercase 'l' console.log('hello world'); }; fjs.parentNode.insertBefore(js, fjs);
<script></script>
I suggest to using jQuery.getScript() for dynamic
as you've mentioned. 我建议您使用jQuery.getScript()进行
dynamic
。
Ex: 例如:
var func = function () {
console.log('do this without the script');
console.log('geting script...');
$.getScript( "//connect.facebook.net/en_US/all.js", function( data, textStatus, jqxhr ) {
console.log('script is loaded...');
console.log( data ); // Data returned
console.log( textStatus ); // Success
console.log( jqxhr.status ); // 200
console.log( "Load was performed." );
});
};
func();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.