Azazel Azazel - 2 years ago 92
HTML Question

Load another JavaScript file and acess var

I'm doing a work for school, and I'm doing a online plataforn to buy games online, I can just use HTML, CSS and JS so for each game e have a JS file with the informations, here is an example:

var info = {
title : "doom",
price : "59.99",
off : "0%"

And my html page is that one:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script src="games/functions.js"></script>

<label id="title"></label>

I have that page to all my games, so I use the GET method to know wich file I need to read. (game.html?id=doom)

I have this code to get the id chosed and load the file:

window.onload = function() {
id = getURLParameter('id');

function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(||[,""])[1].replace(/\+/g, '%20'))||null;

function loadGamefile(filename){
var fileref=document.createElement('script')
fileref.setAttribute("src", filename)
    if (typeof fileref!="undefined")


function loadinformation(){
document.getElementById("title").innerHTML = info.title; //info.title is from the doom.js file

The only problem is he dont change the label, but if I put a button on the btml code and onclick I say its the loadinformation() he load fine, but I want that automatic when the page loads and here is the error I get from console:
functions.js:22 Uncaught ReferenceError: info is not defined
, I think maybe is becouse the browser didn't had time to load the file, I don't know, can someone help me? Thanks and sorry for my english.

Answer Source

The problem is you aren't giving the browser a chance to parse your new script. You can give it a moment to do that using setTimeout.

function loadGamefile(filename) {
    // your other code goes here

    setTimeout(function() {
    }, 500); // wait half of a second

Ideally, you should have your data stored in a JSON file then load it using AJAX instead. There are numerous tutorials covering how to load JSON over AJAX.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download