Include plugin script during export

Get help using Construct 2

Post » Thu Dec 15, 2011 7:51 pm

What I want to do:
- make a plugin
- that tries to load a script from a remote location (to save bandwidth)
- but if it fails loads a remote version instead

I think this sort of thing is fairly common... I've seen it done with Google Analytics a lot. Even C2 does it with jQ. I'm asking for my Playtomic plugin.

The problem:
To include the local version of the script during export I set dependency in edittime.js's GetPluginSettings (I copied the method from the Facebook plugin). However this also automatically adds it to the HTML therefore making the remote loading useless!

What would help me is a way to include a script during export, but NOT automatically add a <script> tag for it to the html.

I couldn't find anything like this using the search or manual.

Ideas, suggestions, etc please wgfunstorm2011-12-16 13:04:28
B
22
S
9
G
5
Posts: 122
Reputation: 5,386

Post » Fri Dec 16, 2011 1:49 pm

The Facebook API actually uses dynamic script loading like you say. You just need to dynamically create a <script> tag and append it to the document head tag, something like this:

[code]var s = document.createElement("script");
s.src = "//myapi.com/foo.js";
document.getElementsByTagName("head")[0].appendChild(s);[/code]

This doesn't have a local fallback but even the Facebook API doesn't have a local fallback - best to just keep it remote IMO.

The script starts downloading and runs asynchronously, so the library won't be ready to use immediately after you run that - you'll need to set a timer and check that something it adds (e.g. a global function) appears. Some APIs give you a callback function which runs when the script loads, though, so best check the documentation. (This is why Facebook also has an 'Is ready' condition - it's false while the script is still downloading.)
Scirra Founder
B
359
S
214
G
72
Posts: 22,952
Reputation: 178,590

Post » Fri Dec 16, 2011 2:03 pm

In the first release I ended up using $.getScript(url, callback) to do remote loading, because like you said it takes a little to load and I like the built-in callback.

But what's the advantage of not having a local fallback?

By copying the method from Facebook I meant how the channel.html file is included locally. I thought remote loading + local fallback would give the best of both. If there's no option for what I want yet, that's cool it's not that important.wgfunstorm2011-12-16 14:14:15
B
22
S
9
G
5
Posts: 122
Reputation: 5,386


Return to How do I....?

Who is online

Users browsing this forum: spacedoubt and 2 guests