0

I have been searching for many hours over several days for this answer and though there are many topics on how to include files in a project (also here at Stack Overflow), I have not yet found THE solution to my problem.

I'm working on a project where I want to include one single object at a time, from many different files (I do not want to include the files themselves, only their content). All the object in all the files have the same name, only the content is different.

It is important that I do not get a SCRIPT tag in the head section of the page as all the content from the files will have the same names. None of the files will have functions anyways, only one single object, that will need to be loaded one at the time and then discarded when the next element is loaded.

The objects will hold the data that will be shown on the page and they will be called from the menu by an 'onclick' event.

function setMenu()   //   The menu is being build.
{
    var html = '';
    html += '<table border="0">';
    for (var i = 0; i<menu.pages.length; i++)    
    {
        html += '<tr class="menuPunkt"><td width="5"></td><td onclick="pageName(this)">'+ menu.pages[i] +'</td><td width="5"></td></tr>';
    }
    //   menu is a global object containing elements such as an array with
    //   all the pages that needs to be shown and styling for the menu.

    html += '</table>';

    document.getElementById("menu").innerHTML = html;
    style.setMenu();   //   The menu is being positioned and styled.
}

Now, when I click on a menu item the pageName function is triggered and I'm sending the HTML element to the function as well, it is here that I want the content from my external file to be loaded into a local variable and used to display content on the page.

The answer I want is "How to load the external obj into the function where I need it?" (It may be an external file, but only in the term of not being included in the head section of the project). I'm still loading the the file from my own local library.

function pageName(elm)   // The element that I clicked is elm.
{
    var page = info.innerHTML;    // I need only the innerHTML from the element.
    var file = 'sites/' + page + '.js';   // The file to be loaded is created.
    var obj = ??      // Here I somehow want the object from the external file to be loaded.
// Before doing stuff the the obj.
    style.content();
}

The content from the external file could look like this:

// The src for the external page: 'sites/page.js'

var obj = new Object()
{
    obj.innerHTML = 'Text to be shown';
    obj.style = 'Not important for problem at hand';
    obj.otherStuff = ' --||-- ';
}

Any help will be appreciated,

Molle

Molle
  • 180
  • 7
  • Have you had a look at Durandal and RequireJS? – Jacques Snyman Oct 22 '13 at 09:50
  • I was thinking that I should be possible to do directly with JS. I would prefer not to use JQuery or other kinds of JS if possible. With all the stuff that can be done with JS, this should be possible too. – Molle Oct 22 '13 at 12:00
  • It is definitely possible, but why re-invent the wheel? – Jacques Snyman Oct 22 '13 at 12:43
  • @Molle What is the actual constraint that you don't want to load the external JS file??? Are you arbitrarily asking for a solution or do you have any specific reason/constraint??? – Rajesh Paul Oct 22 '13 at 13:06
  • I do. There are no functions in the external files so nothing to execute from those files. So I can't see the reason for including them in the project. Further more, all the files contain objects with the same name, so including them will not make any difference. But to load the CONTENT of the files into a local obj, that makes sense. – Molle Oct 22 '13 at 14:01
  • @jaq316. As I mentioned earlier (before the so called "answer" was removed again), I don't care about wheels only in finding the solution to the problem. – Molle Oct 22 '13 at 14:28

1 Answers1

0

Using the following function, you can download the external js file in an ajax way and execute the contents of the file. Please note, however, that the external file will be evaluated in the global scope, and the use of the eval is NOT recommended. The function was adopted from this question.

function strapJS(jsUrl) {

    var jsReq = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
    if (jsReq === null) {
        console.log("Error: XMLHttpRequest could not be initiated.");
    }
    jsReq.onload = function () {
        try {
            eval(jsReq.responseText);
        } catch (e) {
            console.log("Error: The script file contains errors." + e);
        }
    };
    try {

        jsReq.open("GET", jsUrl, true);
        jsReq.send(null);

    } catch (e) {
        console.log("Error: Cannot retrieving data." + e);
    }
}

JSFiddle here

Edit: 1

After some refactoring, I came up with this:

function StrapJs(scriptStr, jsObjName) {
    var self = this;
    self.ScriptStr = scriptStr;
    self.ReturnedVal = null;

    function _init() {
        eval(self.ScriptStr);
        self.ReturnedVal = eval(jsObjName);
    }

    _init();
}

You can then get the script string any way you want and just instantiate a new StrapJs object with the script string and name of the object to return inside the script string. The ReturnedVal property of the StrapJs object will then contain the object you are after.

Example usage:

var extJS = "var obj = " +
    "{ " +
    "    innerHTML : 'Text to be shown', " +
    "    style : 'Not important for problem at hand', " +
    "    otherStuff : ' --||-- ' " +
    "}; ";

var extJS2 = "var obj = " +
    "{ " +
    "    innerHTML : 'Text to be shown 2', " +
    "    style : 'Not important for problem at hand 2', " +
    "    otherStuff : ' --||-- 2' " +
    "}; ";

var strapJS = new StrapJs(extJS, 'obj');
var strapJS2 = new StrapJs(extJS2, 'obj');
console.log(strapJS.ReturnedVal.innerHTML);
console.log(strapJS2.ReturnedVal.innerHTML);

See it in action on this fiddle

Community
  • 1
  • 1
Jacques Snyman
  • 4,115
  • 1
  • 29
  • 49