简体   繁体   中英

Including objects from external .js files

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM