Javascript append javascript file

Append Javascript USING Javascript

What’s the best way to append other javascripts using a JS file? The way I do it right now is working MOST of the time. but some files throw errors like «variable not set yet».. etc..

The way I’m doing it now is:

I’ve also used this to append it to the end of the body:

var js = document.createElement(«sc ript»);
js.setAttribute(«type»,»te xt/javascr ipt»);
js.setAttribute(«src», ‘xxxFile.js’ );

oHead = document.getElementsByTagN ame(‘body’ )[0];
oHead.appendChild( js );

That doesn’t work on some files either though. When I simply put the script tag in the HEAD via HTML, it works fine. But when I use the Document.Write method, it gives me an error. Strange part is , if I dynamically write it first, or write it to the end of the body when the document has loaded.. NEITHER of those work. How can I get past this ?

The particular file that is causing these errors is ‘swfaddress.js’ found here: http://www.asual.com/download/?swfaddress-dist

It only happens on IE. It gives me «Object Not Found».

Avatar of undefined

There is NO way you can do document.write to a web page after the page has loaded.

If some script does do this, then you will need to first have to replace document.write

I have a JavaScript bootstrap file:

This part loads my other JavaScript files:

 function enclude(file_name, loaded)  // File prefix and suffix var pfx = ' '; // Include the file(s) for (var i = 0; i < file_name.length; i++)  if (!loaded)  document.write(pfx + file_name[i] + sfx); > else  var elem = document.createElement("script"); elem.src = pfx + file_name[i] + sfx; document.body.appendChild(elem); > > > (function()  // Core .js files var includes = [ 'file_1.js', 'file_2.js', 'file_3.js', 'file_4.js', 'file_5.js' ]; // Include the files enclude(includes, true); >)(); 

This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.

Ah XCom spotted the mistake
the end script needs to be escaped

>>the end script needs to be escaped

I believe that is shown in my example?

Yes, but xcom already posted that — which was the big deal in the example posted by the asker — your suggestion is a generic way to add, and that was also one of the questions

It didn’t look to me like x_com escaped the backslash in the closing script tag.

Sorry for the delayed response guys.. Thanks for all the replies.

The problem isn’t the code I’m using to load it, I’m pretty sure. I have like 10 files in the array and they all work except this one in particular.

The actual code i’m using to include the files is attached:

An array runs through and adds them already like in Badotz’s example. The problem is this one file in particular throws errors an Object Not Found error on «N.removeEventListener(xxx )» if I do it this way. If I include the script tag to the HTML the normal way, it seems to work fine.

I feel like writing these dynamically vs having them static in the HTML should be almost the same right?

The only thing I can think of is that the JS file I’m including that causes the errors is trying to do something with the document.ready event so it is unable to write whatever HTML when it’s included dynamically.

var myClass =  add: function( lib )  document.write(unescape('%3Cscript type="text/javascript" src="https://www.experts-exchange.com/questions/24063090/'+lib+'"%3E%3C\/script%3E')); > > 

All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone’s boat

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.

GET A PERSONALIZED SOLUTION

There is a library called Scriptaculous.

You load it via a script tag like so .

As you can see, the js file accepts a parameter (load) which has, as its values, additional libraries that have been requested (there are more libraries you can add).

The code to handle this is below .

The require() method is the clever bit.

Using this technique should be what you need.

// script.aculo.us scriptaculous.js v1.8.3, Thu Oct 08 11:23:33 +0200 2009 // Copyright (c) 2005-2009 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // For details, see the script.aculo.us web site: http://script.aculo.us/ var Scriptaculous =  Version: '1.8.3', require: function(libraryName)  try  // inserting via DOM fails in Safari 2.0, so brute force approach document.write(''); > catch(e)  // for xhtml+xml served content, fall back to DOM methods var script = document.createElement('script'); script.type = 'text/javascript'; script.src = libraryName; document.getElementsByTagName('head')[0].appendChild(script); > >, REQUIRED_PROTOTYPE: '1.6.0.3', load: function()  function convertVersionString(versionString)  var v = versionString.replace(/_.*|\./g, ''); v = parseInt(v + '0'.times(4-v.length)); return versionString.indexOf('_') > -1 ? v-1 : v; > if((typeof Prototype=='undefined') || (typeof Element == 'undefined') || (typeof Element.Methods=='undefined') || (convertVersionString(Prototype.Version)  convertVersionString(Scriptaculous.REQUIRED_PROTOTYPE))) throw("script.aculo.us requires the Prototype JavaScript framework >= " + Scriptaculous.REQUIRED_PROTOTYPE); var js = /scriptaculous\.js(\?.*)?$/; $$('head script[src]').findAll(function(s)  return s.src.match(js); >).each(function(s)  var path = s.src.replace(js, ''), includes = s.src.match(/\?.*load=([a-z,]*)/); (includes ? includes[1] : 'builder,effects,dragdrop,controls,slider,sound').split(',').each( function(include) < Scriptaculous.require(path+include+'.js') >); >); > >; Scriptaculous.load(); 

Источник

Handling files in JavaScript

javascript

Invicti Web Application Security Scanner – the only solution that delivers automatic verification of vulnerabilities with Proof-Based Scanning™.

JavaScript is a popular programming language that lets you handle files in the browser. Let’s learn how!

The environment NodeJS is used for different scripts which include file handling. NodeJS is nothing but an environment to run JavaScript code. I hope you have a basic understanding of NodeJS.

Let’s jump into the tutorial to learn about file handling in JavaScript.

File Handling in JavaScript

Handling files includes different operations like creating, reading, updating, renaming, and deleting. We have to access the files from the system which is not possible for us to write it from scratch. So, NodeJS provides a module called fs (file system) for file handling.

Let’s see different methods from the fs module.

fs.open()

The method fs.open() will take two arguments path and mode.

The path is used to locate the file.

The argument mode is used to open the file in different modes like appending, writing, and reading.

If you open any file in a specific mode, then you can perform only one type of operation corresponding to the mode you have passed to the method. Let’s see the list of modes and corresponding operations.

Mode Operation
‘r’ Opens a file in reading mode
‘a’ Opens a file in appending mode
‘w’ Opens a file in writing mode
‘a+’ Opens a file in appending and reading mode
‘w+’ Opens a file in writing and reading mode
‘r+’ Opens a file in reading and writing mode

If the file doesn’t exist on the given path, then it will create a new empty file. Let’s see the code for opening a file in different modes.

const fs = require("fs"); fs.open("sample.txt", "w", (err, file) => < if (err) throw err; console.log(file); >);

The method fs.open() will throw an error if the file doesn’t exist while opening in reading mode. It will create a new empty file in writing and appending modes.

We can perform different operations on the opened file. We will write a complete program at the end of this tutorial after learning some more essential methods from the fs module.

fs.appendFile()

The method fs.appendFile() is used to append the content at the end of the file. If the file doesn’t exist in the given path, then it will create a new one. Append some content to the file using the below code.

const fs = require("fs"); fs.appendFile("sample.txt", "Appending content", (err) => < if (err) throw err; console.log("Completed!"); >);

fs.writeFile()

The method fs.writeFile() is used to write the content to the file. If the file doesn’t exist in the given path, then it will create a new one. Try the below code for writing the content to a file.

const fs = require("fs"); fs.writeFile("sample.txt", "Writing content", (err) => < if (err) throw err; console.log("Completed!"); >);

fs.readFile()

The method fs.readFile() is used to read the content from a file. It will throw an error if the file doesn’t exist in the given path. Examine the following code for the method.

const fs = require("fs"); fs.readFile("sample.txt", (err, data) => < if (err) throw err; console.log(data.toString()); >); 

The method fs.unlink() is used to delete the file. It will throw an error if the file doesn’t exist in the given path. Have a look at the code.

const fs = require("fs"); fs.unlink("sample.txt", (err) => < if (err) throw err; console.log("File deleted!"); >); 

fs.rename()

The method fs.rename() is used to rename the file. It will throw an error if the file doesn’t exist in the given path. Rename the next file with the following code. Be smart!

const fs = require("fs"); fs.rename("sample.txt", "sample_one.txt", (err) => < if (err) throw err; console.log("File renamed!"); >); 

Miscellaneous

Now, you are familiar with different file handling methods from the fs (file system) module. You can perform most of the file operations using the methods that you have seen in this tutorial. As we promised, let’s see an example script that opens a file and read content from it using the fs.open() and fs.readFile() methods respectively.

const fs = require("fs"); fs.open("sample.txt", "r", (err, file) => < if (err) throw err; fs.readFile(file, (err, data) =>< if (err) throw err; console.log(data.toString()); >); >);

Conclusion

That’s it for this tutorial. You can use the file handling methods to automate some of the boring stuff in your day-to-day tasks. I hope you have learned the essential methods for handling files.

Источник

Читайте также:  Вывести случайное число python
Оцените статью