0

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. 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.

What is the solution to ensure that dynamically added script is always available (even after page has loaded)

1
  • 1
    onLoad should be onload Commented Nov 8, 2016 at 9:30

2 Answers 2

1

Remember to double check the property names.

onLoad should be onload (all lowercase).

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>

Sign up to request clarification or add additional context in comments.

Comments

0

I suggest to using jQuery.getScript() for dynamic as you've mentioned.

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.