开发者

Determining if a dependent JavaScript file was included

开发者 https://www.devze.com 2023-03-28 01:34 出处:网络
I have a main JavaScript file, we\'ll call core.js that other file are dependent on. In core.js I am defining an Object that will be required to exist in the dependent files.

I have a main JavaScript file, we'll call core.js that other file are dependent on.

In core.js I am defining an Object that will be required to exist in the dependent files.

core.js:

(function (){
/* base package */
var core = window.core = function() {
    // Throw an error, the core package cannot be instantiated.
    throw new Error("A package cannot be instantiated");
};
})();

utils.js

/* utils package */
core.utils = function() {
    // Throw an error, the core package cannot be instantiated.
     throw("A package cannot be instantiated");
};

/**
 * Utility: StringUtils
 */
core.utils.StringUtils = new Object();
core.utils.StringUtils.prototype = {

    /**
     * ltrim - Removes preceding whitespaces
     */
    ltrim: function(value) {
        var re =开发者_StackOverflow社区 /\s*((\S+\s*)*)/;
        return value.replace(re, "$1");

    },

    /**
     * rtrim - Removes succeeding whitespaces
     */
    rtrim: function(value) {
        var re = /((\s*\S+)*)\s*/;
        return value.replace(re, "$1");

    },

    /**
     * trim - Removes preceding and succeeding whitespaces
     */
    trim: function(value) {
        return core.StringUtils.ltrim(core.StringUtils.rtrim(value));
    }
};

Currently, i am adding an id tag to the <script /> tag

<script id="core.js" src="core.js" type="text/javascript"></script>

and checking it's existence before defining any new items in the core Object.

(function() {
    if (typeof (core) == 'undefined') {
        var script = document.getElementById("core.js");
        if (script == null)
            throw ("core.js is missing.");
        else
            throw ("Unknown Exception. core is undefined.");
    }
})();

Should I be concerned with cross browser compatibility? It is currently working in IE9 and FF5, but I want to make sure it works for all browsers.

Is there an alternative/better way to determine if a file was included or not?


That will work fine, since <script> tags are synchronous any Javascript after that tag will have access to core. If you want another method of doing the same thing, your could take Marc B's suggestion and set a flag in core.js. The flag could also be part of the core object, like core.is_loaded = true; Then you just check if(core.is_loaded) in your other files.

0

精彩评论

暂无评论...
验证码 换一张
取 消