Skip to main content
GameDev.net gamedev.net
🔒 Locked

Javascript & HTML5: Loading of external scripts with javascript

Started by Dauid Nov 3, 2012 at 2:44 PM 2 replies 3.3k views
Original Post
Dauid
Dauid
Hello,

I am making a game in HTML5 & Javascript and I'm having some issues in loading up external scripts.
The way the game is built is the data of all the game levels is stored in seperate javascript files where
a level object is created and level information is specified.

So inside my game engine I want to load 'on the fly' one level file and use that data to start a level.

I have tried using jQuery's getScript() but I only get a "Access to restricted URI denied"- exception.
I have tried having an empty script tag then changing the src-attribute to the specified path, because I read somewhere that it will load automatically if the src-attribute is changed.

One solution is to just load every level file in the HEAD-tag but there will be alot of levels and I like to compress my code as much as possible and also would very much like to learn how to do this.

Grateful for replies
David
PlaycraftLabs
PlaycraftLabs
I'm not entirely sure of the problem you're having. You can definitely load javascript files dynamically, and then execute them.

Why not just dynamically construct a script element, set the src attribute and then append it to the DOM, i.e.

[source lang="jscript"]
var src = 'my.js;
var script = document.createElement("script");
script.type = "application/javascript";
script.src = src;

script.onload = function()
{
// ya!
};

script.onerror = function ()
{
throw('Could not load javascript file: ' + script.src);
};

document.getElementsByTagName("head")[0].appendChild(script);
[/source]

Am I missing something?
DangerDoom
DangerDoom

Out of the box, JavaScript can't do this, and its a gigantic hole in the language.



Good news... you can load scripts dynamically by injecting the tag into the DOM. The example by Martin Wells will work, but personally I would do two things differently:



script.type = "text/javascript";


because some webservers automatically compress text based responses.
and...


window.document.body.appendChild(script);


because it's just good practice to append scripts to the body tag.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.