Passed
Push — master ( 44be85...d64e50 )
by Tomasz
24:29
created

load.js ➔ getTarget   A

Complexity

Conditions 3

Size

Total Lines 11
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 8
dl 0
loc 11
rs 10
c 0
b 0
f 0
cc 3
1
// TODO: if function not exist try to load from main folder with the name {NameOfFunction}.js
2
var Load = function (target, success, error) {
3
    //url is URL of external file, success is the code
4
    //to be called from the file, location is the location to
5
    //insert the <script> element
6
    this.cfg = {};
7
    this.cfg.target = target;
8
    this.cfg.delay = 0;
9
    this.cfg.cache = 1;
10
11
    this.success = success;
12
    this.error = error;
13
14
15
    var self = this;
16
17
    this.target = function (target) {
18
        self.cfg.target = target;
19
        return this;
20
    };
21
22
    this.delay = function (delay) {
23
        self.cfg.delay = delay;
24
        return this;
25
    };
26
27
    this.cache = function (cache) {
28
        self.cfg.cache = cache;
29
        return this;
30
    };
31
32
    this.cacheOff = function () {
33
        self.cfg.cache = 0;
34
35
        return this;
36
    };
37
38
    this.cacheOn = function () {
39
        self.cfg.cache = 1;
40
41
        return this;
42
    };
43
44
    this.js = function (url) {
45
        if (typeof self.cfg.delay === 'number' && self.cfg.delay > 1) {
46
            setTimeout(function () {
47
                    console.log('delayed', self.cfg.delay, url);
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
48
                    self.loadJs(url, self.cfg.target, self.success, self.error);
49
                },
50
                self.cfg.delay
51
            );
52
        } else {
53
            console.log('loaded', url);
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
54
            self.loadJs(url, self.cfg.target, self.success, self.error);
55
        }
56
        return this;
57
    };
58
    this.javascript = this.js;
59
    this.script = this.js;
60
61
62
    this.css = function (url) {
63
        if (typeof self.cfg.delay === 'number' && self.cfg.delay > 1) {
64
            setTimeout(function () {
65
                    console.log('delayed', self.cfg.delay, url);
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
66
                    self.loadCss(url, self.cfg.target, self.success, self.error);
67
                },
68
                self.cfg.delay
69
            );
70
        } else {
71
            console.log('loaded', url);
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
72
            self.loadCss(url, self.cfg.target, self.success, self.error);
73
        }
74
        return this;
75
        //
76
        // if (typeof url === 'object') {
77
        //     //console.log('obj:', obj);
78
        //
79
        //     for (var i in url) {
80
        //
81
        //         console.log('load js url[i]', url[i]);
82
        //
83
        //         try {
84
        //             var exe = includeStyle(url[i], self.cfg.target, success, error);
85
        //             console.log('load js ', url[i], exe);
86
        //         } catch (err) {
87
        //             console.error('!load js ', url[i], err);
88
        //         }
89
        //     }
90
        // } else {
91
        //     includeHtml(url, self.cfg.target, success, error);
92
        //     // console.error('apiunit obj: is not object:', obj);
93
        // }
94
        // return this;
95
    };
96
    this.style = this.css;
97
98
    // TODO: check if is loaded
99
    this.loadJs = function (url, target, success, error) {
100
        var suffix = '';
101
        if (typeof self.cfg.cache === 'number' && self.cfg.cache !== 1) {
102
            suffix = '?' + time();
103
        }
104
105
        if (typeof url === 'object') {
106
            //console.log('obj:', obj);
107
108
            for (var i in url) {
0 ignored issues
show
Complexity introduced by
A for in loop automatically includes the property of any prototype object, consider checking the key using hasOwnProperty.

When iterating over the keys of an object, this includes not only the keys of the object, but also keys contained in the prototype of that object. It is generally a best practice to check for these keys specifically:

var someObject;
for (var key in someObject) {
    if ( ! someObject.hasOwnProperty(key)) {
        continue; // Skip keys from the prototype.
    }

    doSomethingWith(key);
}
Loading history...
109
110
                console.log('load js url[i]', url[i]);
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
111
112
                try {
113
                    var exe = includeJs(url[i] + suffix, target, success, error);
114
                    console.log('load js ', url[i], exe);
115
                } catch (err) {
116
                    console.error('!load js ', url[i], err);
117
                }
118
            }
119
        } else {
120
            includeJs(url + suffix, target, success, error);
121
            // console.error('apiunit obj: is not object:', obj);
122
        }
123
124
        return this;
125
    };
126
127
    this.loadCss = function (url, target, success, error) {
128
        var suffix = '';
129
        if (typeof self.cfg.cache === 'number' && self.cfg.cache !== 1) {
130
            suffix = '?' + time();
131
        }
132
133
        if (typeof url === 'object') {
134
            //console.log('obj:', obj);
135
136
            for (var i in url) {
0 ignored issues
show
Complexity introduced by
A for in loop automatically includes the property of any prototype object, consider checking the key using hasOwnProperty.

When iterating over the keys of an object, this includes not only the keys of the object, but also keys contained in the prototype of that object. It is generally a best practice to check for these keys specifically:

var someObject;
for (var key in someObject) {
    if ( ! someObject.hasOwnProperty(key)) {
        continue; // Skip keys from the prototype.
    }

    doSomethingWith(key);
}
Loading history...
137
138
                console.log('load CSS url[i]', url[i]);
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
139
140
                try {
141
                    var exe = includeStyle(url[i] + suffix, target, success, error);
142
                    console.log('load CSS ', url[i], exe);
143
                } catch (err) {
144
                    console.error('!load CSS ', url[i], err);
145
                }
146
            }
147
        } else {
148
            includeStyle(url + suffix, target, success, error);
149
            // console.error('apiunit obj: is not object:', obj);
150
        }
151
152
        return this;
153
    };
154
155
156
    this.html = function (url) {
157
        if (typeof url === 'object') {
158
            //console.log('obj:', obj);
159
160
            for (var i in url) {
0 ignored issues
show
Complexity introduced by
A for in loop automatically includes the property of any prototype object, consider checking the key using hasOwnProperty.

When iterating over the keys of an object, this includes not only the keys of the object, but also keys contained in the prototype of that object. It is generally a best practice to check for these keys specifically:

var someObject;
for (var key in someObject) {
    if ( ! someObject.hasOwnProperty(key)) {
        continue; // Skip keys from the prototype.
    }

    doSomethingWith(key);
}
Loading history...
161
162
                console.log('load js url[i]', url[i]);
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
163
164
                try {
165
                    var exe = includeHtml(url[i], self.cfg.target, success, error);
166
                    console.log('load js ', url[i], exe);
167
                } catch (err) {
168
                    console.error('!load js ', url[i], err);
169
                }
170
            }
171
        } else {
172
            includeHtml(url, self.cfg.target, success, error);
173
            // console.error('apiunit obj: is not object:', obj);
174
        }
175
        return this;
176
    };
177
178
179
    this.image = function (url) {
180
        if (typeof self.cfg.delay === 'number' && self.cfg.delay > 1) {
181
            setTimeout(function () {
182
                    console.log('image delayed', self.cfg.delay, url);
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
183
                    self.loadImage(url, self.cfg.target, self.success, self.error);
184
                },
185
                self.cfg.delay
186
            );
187
        } else {
188
            console.log('image loaded', url, self.cfg.delay);
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
189
            self.loadImage(url, self.cfg.target, self.success, self.error);
190
        }
191
        return this;
192
    };
193
194
    this.loadImage = function (url, target, success, error) {
195
        if (typeof url === 'object') {
196
            //console.log('obj:', obj);
197
198
            for (var i in url) {
0 ignored issues
show
Complexity introduced by
A for in loop automatically includes the property of any prototype object, consider checking the key using hasOwnProperty.

When iterating over the keys of an object, this includes not only the keys of the object, but also keys contained in the prototype of that object. It is generally a best practice to check for these keys specifically:

var someObject;
for (var key in someObject) {
    if ( ! someObject.hasOwnProperty(key)) {
        continue; // Skip keys from the prototype.
    }

    doSomethingWith(key);
}
Loading history...
199
200
                console.log('load js url[i]', url[i]);
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
201
202
                try {
203
                    var exe = includeImage(url[i], target, success, error);
0 ignored issues
show
Bug introduced by
The call to includeImage seems to have too many arguments starting with success.
Loading history...
204
                    console.log('load js ', url[i], exe);
205
                } catch (err) {
206
                    console.error('!load js ', url[i], err);
207
                }
208
            }
209
        } else {
210
            includeImage(url, self.cfg.target, success, error);
211
            // console.error('apiunit obj: is not object:', obj);
212
        }
213
        return this;
214
    };
215
216
    this.img = this.image;
217
218
    return this;
219
};
220
221
function includeJs(url, target, success, error) {
222
    var scriptTag = document.createElement('script');
223
    scriptTag.src = url;
224
    scriptTag.type = 'text/javascript';
225
226
    scriptTag.onerror = error;
227
    scriptTag.onload = success;
228
    scriptTag.onreadystatechange = success;
229
230
    return getTarget(target).appendChild(scriptTag);
231
}
232
233
function isEmpty(val) {
234
    return val == null || typeof val === 'undefined' || val.length < 1;
0 ignored issues
show
Best Practice introduced by
Comparing val to null using the == operator is not safe. Consider using === instead.
Loading history...
235
}
236
237
function getTarget(target) {
238
    if (isEmpty(target)) {
239
        console.log('HEAD');
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
240
        target = document.getElementsByTagName('head')[0];
241
        if (isEmpty(target)) {
242
            console.log('BODY');
243
            target = document.body;
244
        }
245
    }
246
    return target;
247
}
248
249
function createTagLink(url, success, error) {
250
    var link = document.createElement('link');
251
    link.href = url;
252
    link.rel = 'stylesheet';
253
    link.type = 'text/css';
254
    link.media = 'all';
255
256
    link.onerror = error;
257
    link.onload = success;
258
    link.onreadystatechange = success;
259
260
    return link;
261
}
262
263
264
function getXHRObject() {
265
    var xhrObj = false;
0 ignored issues
show
Unused Code introduced by
The assignment to variable xhrObj seems to be never used. Consider removing it.
Loading history...
266
    try {
267
        xhrObj = new XMLHttpRequest();
268
    } catch (e) {
269
        var progid = ['MSXML2.XMLHTTP.5.0', 'MSXML2.XMLHTTP.4.0',
270
            'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP', 'Microsoft.XMLHTTP'];
271
        for (var i = 0; i < progid.length; ++i) {
272
            try {
273
                xhrObj = new ActiveXObject(progid[i]);
0 ignored issues
show
Bug introduced by
The variable ActiveXObject seems to be never declared. If this is a global, consider adding a /** global: ActiveXObject */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
274
            } catch (e) {
275
                continue;
276
            }
277
            break;
278
        }
279
    } finally {
280
        return xhrObj;
0 ignored issues
show
Comprehensibility Bug introduced by
Usage of the return statement in a finally clause is discouraged. This construct may mask errors and makes debugging difficult.
Loading history...
281
    }
282
}
283
284
// TODO: replce path to id name and check if ID exist
285
// FASTEST loading:
286
// https://www.oreilly.com/library/view/even-faster-web/9780596803773/ch04.html
287
function includeStyle(url, target, success, error) {
288
    // console.log(target, target == null);
289
    // return false;
290
291
    // var xhrObj = getXHRObject(); // defined in the previous example
292
    // xhrObj.onreadystatechange =
293
    //     function () {
294
    //         if (xhrObj.readyState == 4) {
295
    //             // var scriptElem = document.createElement('script');
296
    //             var scriptElem = document.createElement('style');
297
    //             document.getElementsByTagName('head')[0].appendChild(scriptElem);
298
    //             scriptElem.text = xhrObj.responseText;
299
    //         }
300
    //     };
301
    // xhrObj.open('GET', url, true); // must be same domain as main page
302
    // return xhrObj.send('');
303
304
305
    var link = createTagLink(url, success, error);
306
    return getTarget(target).appendChild(link);
307
}
308
309
310 View Code Duplication
function includeHtml(url, target, success, error) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
311
    var xhttp;
312
313
    var el = new E(target);
314
    var elmnt = el.first();
315
316
    if (typeof success !== 'function') {
317
        success = function () {
318
            console.log('includeHtml success', "included");
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
319
        }
320
    }
321
322
    if (typeof error !== 'function') {
323
        error = function () {
324
            console.log('includeHtml error', "Page not found.");
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
325
        }
326
    }
327
    console.log('includeHtml url', url);
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
328
329
    if (url) {
330
        /* Make an HTTP request using the attribute value as the url name: */
331
        xhttp = new XMLHttpRequest();
332
        xhttp.onreadystatechange = function () {
333
            console.log('includeHtml el_id', target);
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
334
335
            if (this.readyState == 4) {
336
                if (this.status == 200) {
337
338
                    elmnt.insertAdjacentHTML('beforeend', this.responseText);
339
340
                    success(this);
0 ignored issues
show
Bug introduced by
The call to success seems to have too many arguments starting with this.
Loading history...
341
                }
342
                if (this.status == 404) {
343
                    elmnt.innerHTML = "includeHtml Page not found.";
344
                    error(this);
0 ignored issues
show
Bug introduced by
The call to error seems to have too many arguments starting with this.
Loading history...
345
                }
346
                /* Remove the attribute, and call this function once more: */
347
                // includeHtml(url, success, error);
348
            }
349
        }
350
        xhttp.open("GET", url, true);
351
        xhttp.send();
352
        /* Exit the function: */
353
        return this;
354
    }
355
    return false;
356
357
}
358
359
// function includeImage(url, target, success, error) {
360
361
function includeImage(url, target) {
362
    console.log('includeImg url: ', url);
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
363
    var el = new E(target);
364
    var elmnt = el.first();
365
366
    let img = new Image;
0 ignored issues
show
Bug introduced by
The variable Image seems to be never declared. If this is a global, consider adding a /** global: Image */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
367
    img.onload = function () {
368
        console.log("includeImg onload: ", url);
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
369
        elmnt.appendChild(img);
370
    };
371
372
    return img.src = url;  // erst nach dem Event Listener!
373
374
}
375
376
377
var time = Date.now || function () {
378
    return +new Date;
379
};
380
381
382 View Code Duplication
var E = function (selector, area, error, success) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
383
    this.cfg = {};
384
    this.cfg.area = document;
385
    this.cfg.selector = selector;
386
    this.cfg.exist = false;
387
388
    this.success = function (elem) {
389
        console.log("Element elem: ", elem);
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
390
    };
391
392
    this.error = function (elem) {
393
        console.error("! Element elem: ", elem);
394
    };
395
396
    if (typeof success === 'function') {
397
        this.success = success;
398
    }
399
400
    if (typeof error === 'function') {
401
        this.error = error;
402
    }
403
404
405
    var self = this;
406
407
    this.selector = function (selector) {
408
        self.cfg.selector = selector;
409
        return this;
410
    }
411
412
    this.first = function (error, success) {
413
        if (typeof success !== 'function') {
414
            success = self.success;
415
        }
416
        if (typeof error !== 'function') {
417
            error = self.error;
418
        }
419
420
        const elem = document.querySelector(self.cfg.selector);
421
422
        console.log('E first self.cfg.selector', self.cfg.selector);
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
423
        console.log('E first elem', elem);
424
425
        if (elem !== null) {
426
            self.cfg.exist = true;
427
            success(elem);
428
            return elem;
429
        } else {
0 ignored issues
show
Comprehensibility introduced by
else is not necessary here since all if branches return, consider removing it to reduce nesting and make code more readable.
Loading history...
430
            self.cfg.exist = false;
431
            error();
432
        }
433
434
        return elem;
435
    }
436
437
    this.all = function (error, success) {
438
        if (typeof success !== 'function') {
439
            success = self.success;
440
        }
441
        if (typeof error !== 'function') {
442
            error = self.error;
443
        }
444
445
        const elem = document.querySelectorAll(self.cfg.selector);
446
447
        console.log('E all self.cfg.selector', self.cfg.selector);
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
448
        console.log('E all elem', elem);
449
450
        if (elem !== null) {
451
            self.cfg.exist = true;
452
            success(elem);
453
        } else {
454
            self.cfg.exist = false;
455
            error(elem);
456
        }
457
458
        return elem;
459
    }
460
};