1

I want to call a third party js in the body tag of my code after I define a particular object. Whats the best way to add the third party js inside my js file? I read that below is one way to do it but it is harmful.

        var myObject = { /*this is my object */};
        var js = document.createElement("script");

        js.type = "text/javascript";
        js.src = "thirdparty.js";

        document.body.appendChild(js);

I'm a js newbie. I researched a bit & saw options such as reuire js etc but I'm not very clear. Can any one suggest me the correct & simplest way to include third party js in my js file? way to do it? I want this js to be called only after I define myObject in the body. \

Like this: @veritas

myObject = { //my object };
add_html += ' < div id="xyz" >';
add_html += '< /div >';
$some_div.find('li').eq(2).after( add_html );
$('#xyz').append(myObject);
var js = document.createElement("script");
js.type = "text/javascript";
js.src = "thirdparty.js";
document.body.appendChild(js);
3
  • possible duplicate of Load external js file with jQuery Commented Oct 3, 2014 at 17:23
  • There is nothing particularly "harmful" about the above, assuming the script source is secured - however, the script will be loaded asynchronously which should be taken into consideration. In any case, I recommend using an "AMD" module loader in such cases such as RequireJS. There are many different module loaders, and one or multiple already handle this case. Also, with correct (or more aggressive versioned) caching the download penalty is effectively only payed once, so it may not be worth "optimizing". Commented Oct 3, 2014 at 17:36
  • this is a very good question Commented Apr 8, 2018 at 5:11

4 Answers 4

3

If you want to insert the 3rd party library with JS, you can add an event listener to make sure it's loaded and then run your code.

var myObject = { /*this is my object */},
    js = document.createElement("script");

js.type = "text/javascript"; 
js.onload = function () {
    myObject.callMethod(); 
}

document.body.appendChild(js);
js.src = "thirdparty.js";

The most important part is to put the js.src = setting after attaching your listener because the resource may trigger load before your manage to add a event listener to it.

EDIT

I'm not clear what does this part do js.onload = function () { myObject.callMethod(); } .. What is callMethod()? .

.onload part

Every resource element like script will trigger an event load after successfuly loading the content inside your document. The .onload part is adding an event listener to that particular event (NOTE: this code can be also written differently eg. js.addEventListener("load", callback)). Why do we want to trigger the code after load? Simple, because the browser is doing the fetch and execute asynchronously and the objects or methods you expect to get from the thirdparty.js may not be ready before next operation in your script (so you would get undefined values).

.callMethod() part

This is just my dummy code, I was assuming you want to run a method from myObject that uses some thirdlibrary objects and methods`.

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

7 Comments

thanks for your answer. I'm not clear what does this part do js.onload = function () { myObject.callMethod(); } .. What is callMethod()? . My object has only properties & no methods.
sure. Will wait for that.
no I'm don't have any methods in my object. I just have a few properties set & the third party js would fetch those properties in my object. Thats the reason why I need to define my object before calling their js. so in that case should I be including any thing in the onload?
oh... no ;) You do not need the .onload or any other event listeners
so should it just be same as the code I've written in my question? Correct? It's not going to override anything as its in the body correct?
|
1

Why all the fuss ? Go simple

<script>
  var myObject = { /*this is my object */};
  if (myObject.otherLibIsNeeded) {
    var newScript = document.createElement('script');
    newScript.src = '/path/to/thirdparty.js';
    document.head.append(newScript);
  }
</script>

6 Comments

It would be nice to just load the script if it was required though, bandwidth can be costly for mobile users api.jquery.com/jQuery.getScript
@andrew you can go do this without jQuery ;) adding external scripts with Vanilla JS is not so hard
@veritas completely agree, just added the link as jQuery was tagged
Oh, seeing the answer of @veritas, I realize I may not have understood where the "if needed" should be. Adding +1 to your answer.
@laruiss thanks for your answer. Can I just call the third party js code right after my object definition without putting in the if condition? Not sure what is the need of if condition here? I have my object populated any ways.
|
0

The best way to do this is to just include the third party library in the head of the HTML file where you include your own js, making sure it is before yours:

<script src="thirdparty.js"></script>
<script src="myScript.js"></script>

Comments

0

One more easy way is to do it using ScriptManJS library. It makes sure dependencies are loaded correctly and you do not have to bother about it when using ScriptManJS.

1) Add script tag to the head section of html to include the library:

<script type="text/javascript" src="scriptman.min.js"></script>

2) Somewhere in beginning of code add:

new ScriptMan();

3) Perform inclusions in one of the possible syntaxes. I will provide several options how to do that just a broader picture. I am sure you will choose the one which will best suit your needs:

Option 1:

Just include two files - no additional code is needed when they are loaded.

S.require( [
    'file_with_your_object.js',
    'third_party.js'
], {
    sync: true
} );

// Files may not be loaded yet when executing code here

Option 2:

If object is defined in main file, it becomes simple as this.

var yourObject = { /* Object contents */ };
S.require( 'third_party.js' );

// Files may not be loaded yet when executing code here

If you do not like the fact that file may not be loaded yet below this fragment, modify the last line to this:

S.require( 'third_party.js' ).then( function() {
    // Here third_party.js will definitely be loaded
} );

// Here third.party.js may not be ready yet

Option 3

Same as option 1 - different syntax.

S.require( 'file_with_your_object.js' ).then( function() {
    S.require( 'third_party.js' );
} );

Option 4:

How I would do it with ScriptManJS.

file_with_your_object.js

return { /* Object contents */ };

main file (i.e. index.html)

S.require( 'file_with_your_object.js' ).then( function( yourObject ) {
    S.require( 'third_party.js' ).then( function() {
        // Everything is loaded and yourObject contains your object here
    } );
} );

Or even like this (in main file):

S.require( [
    'file_with_your_object.js',
    'third_party.js'
], {
    sync: true
} ).then( function( yourObject ) {
    // Everything is loaded and yourObject contains your object here
} );

If for some reason third party library would not like to be included like that (low probability), you can add one more option next to sync: ... { sync: true, nakedFiles: [ 'third_party.js' ] } ...

Hope this helps :)

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.