Javascript & HTML5: Loading of external scripts with javascript

Started by
2 comments, last by DangerDoom 11 years, 5 months ago
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
Advertisement
Out of the box, JavaScript can't do this, and its a gigantic hole in the language. Fortunately it is something they are looking to fix in ECMAScript 6.

At the end of the day, you either include them as <SCRIPT> entries like you are currently doing, or you ajax load them.

In the end, you often rely on your framework of choice to provide a loader for you. I recently have been working with YUI, which providers it's own loaded, and you can see the process of adding your own scripts with the YUI loader here if interested (see the section A little longer, a lot less ugly ).

That said, if your library of choice doesn't have a loader, or the loader isn't ideal, check out Require.js. It's probably as close to a defacto standard as you can get. Here is a tutorial that is jquery specific.
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?

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.

This topic is closed to new replies.

Advertisement