function include(filename){var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');script.src = filename;script.type = 'text/javascript';
head.appendChild(script)}
<script type="module">import { hello } from './hello.mjs'; // Or the extension could be just `.js`hello('world');</script>
// hello.mjs -- or the extension could be just `.js`export function hello(text) {const div = document.createElement('div');div.textContent = `Hello ${text}`;document.body.appendChild(div);}
fetchInject(['https://cdn.jsdelivr.net/momentjs/2.17.1/moment.min.js']).then(() => {console.log(`Finish in less than ${moment().endOf('year').fromNow(true)}`)})
function dynamicallyLoadScript(url) {var script = document.createElement("script"); // create a script DOM nodescript.src = url; // set its src to the provided URL
document.head.appendChild(script); // add it to the end of the head section of the page (could change 'head' to 'body' to add it to the end of the body section instead)}
var js = document.createElement("script");
js.type = "text/javascript";js.src = jsFilePath;
document.body.appendChild(js);
var s = new MySuperObject();
Error : MySuperObject is undefined
function loadScript(url, callback){// Adding the script tag to the head as suggested beforevar head = document.head;var script = document.createElement('script');script.type = 'text/javascript';script.src = url;
// Then bind the event to the callback function.// There are several events for cross browser compatibility.script.onreadystatechange = callback;script.onload = callback;
// Fire the loadinghead.appendChild(script);}
var require = (function() {var _required = {};return (function(url, callback) {if (typeof url == 'object') {// We've (hopefully) got an array: time to chain!if (url.length > 1) {// Load the nth file as soon as everything up to the// n-1th one is done.require(url.slice(0, url.length - 1), function() {require(url[url.length - 1], callback);});} else if (url.length == 1) {require(url[0], callback);}return;}if (typeof _required[url] == 'undefined') {// Haven't loaded this URL yet; gogogo!_required[url] = [];
var script = new Element('script', {src: url,type: 'text/javascript'});script.observe('load', function() {console.log("script " + url + " loaded.");_required[url].each(function(cb) {cb.call(); // TODO: does this execute in the right context?});_required[url] = true;});
$$('head')[0].insert(script);} else if (typeof _required[url] == 'boolean') {// We already loaded the thing, so go ahead.if (callback) {callback.call();}return;}
if (callback) {_required[url].push(callback);}});})();
用法:
<script src="prototype.js"></script><script src="require.js"></script><script>require(['foo.js','bar.js'], function () {/* Use foo.js and bar.js here */});</script>
$("head").append($("<script></script>").attr("src", url));
/* Note that following line of code is incorrect because it doesn't escape the* HTML attribute src correctly and will fail if `url` contains special characters:* $("head").append('<script src="' + url + '"></script>');*/
function require(script) {$.ajax({url: script,dataType: "script",async: false, // <-- This is the keysuccess: function () {// all good...},error: function () {throw new Error("Could not load script " + script);}});}
//set array to be updated when we add or remove plugin filesvar pluginNames = ["lettering", "fittext", "butterjam", etc.];
//one script tag for each plugin$.each(pluginNames, function(){$('head').append('<script src="js/plugins/' + this + '.js"></script>');});
/*** @fileoverview This file stores global functions that are required by other libraries.*/
if (typeof(jQuery) === 'undefined') {throw 'jQuery is required.';}
/** Defines the base script directory that all .js files are assumed to be organized under. */var BASE_DIR = 'js/';
/*** Loads the specified file, outputting it to the <head> HTMLElement.** This method mimics the use of using in C# or import in Java, allowing* JavaScript files to "load" other JavaScript files that they depend on* using a familiar syntax.** This method assumes all scripts are under a directory at the root and will* append the .js file extension automatically.** @param {string} file A file path to load using C#/Java "dot" syntax.** Example Usage:* imports('core.utils.extensions');* This will output: <script type="text/javascript" src="/js/core/utils/extensions.js"></script>*/function imports(file) {var fileName = file.substr(file.lastIndexOf('.') + 1, file.length);
// Convert PascalCase name to underscore_separated_namevar regex = new RegExp(/([A-Z])/g);if (regex.test(fileName)) {var separated = fileName.replace(regex, ",$1").replace(',', '');fileName = separated.replace(/[,]/g, '_');}
// Remove the original JavaScript file name to replace with underscore versionfile = file.substr(0, file.lastIndexOf('.'));
// Convert the dot syntax to directory syntax to actually load the fileif (file.indexOf('.') > 0) {file = file.replace(/[.]/g, '/');}
var src = BASE_DIR + file + '/' + fileName.toLowerCase() + '.js';var script = document.createElement('script');script.type = 'text/javascript';script.src = src;
$('head').find('script:last').append(script);}
define(['lib/dependency1', 'lib/dependency2'], function (d1, d2) {
//Your actual script goes here.//The dependent scripts will be fetched if necessary.
return libraryObject; //For example, jQuery object});
var s=["Hscript.js","checkRobert.js","Hscript.js"];for(i=0;i<s.length;i++){var script=document.createElement("script");script.type="text/javascript";script.src=s[i];document.getElementsByTagName("head")[0].appendChild(script)};
var f2obj = "file2";$.getScript("file3.js", function(){
alert(f3obj);
// Use anything defined in file3.});
file1.js:
$.getScript("file2.js", function(){alert(f3obj); //This will probably fail because file3 is only guaranteed to have loaded inside the callback in file2.alert(f2obj);
// Use anything defined in the loaded script...});
$.extend(true,{import_js : function(scriptpath, reAddLast){if (typeof reAddLast === "undefined" || reAddLast === null){reAddLast = true; // Default this value to true. It is not used by the end user, only to facilitate recursion correctly.}
var found = false;if (reAddLast == true) // If we are re-adding the originating script we do not care if it has already been added.{found = $('script').filter(function () {return ($(this).attr('src') == scriptpath);}).length != 0; // jQuery to check if the script already exists. (replace it with straight JavaScript if you don't like jQuery.}
if (found == false) {
var callingScriptPath = $('script').last().attr("src"); // Get the script that is currently loading. Again this creates a limitation where this should not be used in a button, and only before document.ready.
document.writeln("<script type='text/javascript' src='" + scriptpath + "'></script>"); // Add the script to the document using writeln
if (reAddLast){$.import_js(callingScriptPath, false); // Call itself with the originating script to fix the order.throw 'Readding script to correct order: ' + scriptpath + ' < ' + callingScriptPath; // This halts execution of the originating script since it is getting reloaded. If you put a try / catch around the call to $.import_js you results will vary.}return true;}return false;}});
用法:
文件3:
var f3obj = "file3";
// Define other stuff$(function(){f3obj = "file3docready";});
$.import_js('js/file2.js');
// Use objects from file2 or file3alert(f3obj); // "file3"alert(f2obj); // "file2"
$(function(){// Use objects from file2 or file3 some more.alert(f3obj); //"file3docready"alert(f2obj); //"file2docready"});
import name from "module-name";import { member } from "module-name";import { member as alias } from "module-name";import { member1 , member2 } from "module-name";import { member1 , member2 as alias2 , [...] } from "module-name";import name , { member [ , [...] ] } from "module-name";import "module-name" as name;
// Load a JavaScript file from other JavaScript filefunction loadScript(urlPack, callback) {var url = urlPack.shift();var subCallback;
if (urlPack.length == 0) subCallback = callback;else subCallback = function () {console.log("Log script: " + new Date().getTime());loadScript(urlPack, callback);}
// Adding the script tag to the head as suggested beforevar head = document.getElementsByTagName('head')[0];var script = document.createElement('script');script.type = 'text/javascript';script.src = url;
// Then bind the event to the callback function.// There are several events for cross browser compatibility.script.onreadystatechange = subCallback;script.onload = subCallback;
// Fire the loadinghead.appendChild(script);}
import xxx from "../lib/your-library.js" //get default exportimport {specificPart} from '../lib/your-library.js' //get named exportimport * as _name from '../lib/your-library.js' //get full export to alias _name
class Person {constructor(name) {this.name = name;}
build() {return new Person(this);}}
module.exports = Person;
在另一个 JavaScript文件中,导入如下:
import { Person } from 'Person';
您还可以要求文件,如:
const Person = require('./Person');
如果您使用的是较旧的JavaScript版本,您可以使用必填项:
requirejs(["helper/util"], function(util) {// This function is called when scripts/helper/util.js is loaded.// If util.js calls define(), then this function is not fired until// util's dependencies have loaded, and the util argument will hold// the module value for "helper/util".});
如果你想坚持使用旧版本的东西,比如jQuery,你也可以使用getScript:
jQuery.getScript('./another-script.js', function() {// Call back after another-script loaded});
// main.js file
export function add (a, b) {return a + b;}
export default function multiply (a, b) {return a * b;}
// test.js file
import {add}, multiply from './main'; // For named exports between curly braces {export1, export2}// For default exports without {}
console.log(multiply(2, 2)); // logs 4
console.log(add(1, 2)); // logs 3
// main.js file
function add (a, b) {return a + b;}
module.exports = add; // Here we add our 'add' function to the exports object
// test.js file
const add = require('./main');
console.log(add(1,2)); // logs 3
dynamicallyLoadScript("script1.js").then(() => dynamicallyLoadScript("script2.js")).then(() => foo()) // foo can be a function defined in either script1, script2.then(() => dynamicallyLoadScript("script3.js")).then(() => {if (var1){ // var1 can be a global variable defined in either script1, script2, or script3bar(var1); // bar can be a function defined in either script1, script2, or script3} else {foo(var1);}})//more .then chains...
// Based on: https://javascript.info/promise-error-handling#unhandled-rejectionswindow.addEventListener('unhandledrejection', function(event) {// the event object has two special properties:console.error(event.promise);// the promise that generated the errorconsole.error(event.reason); // the unhandled error object});
现在,您将收到任何脚本加载错误的通知。
快捷功能
如果您在加载后不立即执行代码而加载大量脚本,则此速记函数可能会派上用场:
function dynamicallyLoadScripts(urls) {if (urls.length === 0)return;
let promise = dynamicallyLoadScript(urls[0]);urls.slice(1).forEach(url => {promise = promise.then(() => dynamicallyLoadScript(url));});}
onload: function () The onload event occurs when a script has been loaded. Default is undefined.
onerror: function ( str, e ) The onerror event occurs when an error has been occurred. The default is undefined.
str: error details
e: event
appendTo: The node to which the new script will be append. The default is the head node.
例如
loadScript.async( "JavaScript.js",{onload: function () {
var str = 'file has been loaded successfully';console.log( str );},onerror: function ( str, e ) {
console.error( str );},} );
function include(filename){var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');script.src = filename;script.type = 'text/javascript';
head.appendChild(script)}
//this is math.js
//varslet a = 1;let b = 3;
//start of codeconst additionfile = require('addition.js');window.alert("You added " + a + " and " + b + " together, to get " + additionfile.add(a,b) + "!");