Greasy Fork

docsReady

A JavaScript to run script when docs is ready

目前为 2018-06-06 提交的版本。查看 最新版本

此脚本不应直接安装,它是一个供其他脚本使用的外部库。如果您需要使用该库,请在脚本元属性加入:// @require https://update.greasyfork.icu/scripts/29782/603417/docsReady.js

// ==UserScript==
// @name			docsReady
// @namespace		[email protected]
// @description		A JavaScript to run script when docs is ready
// @author			xymopen
// @version			1.1.0
// @grant			none
// @license			BSD 2-Clause
// ==/UserScript==

// @updateURL		https://raw.githubusercontent.com/xymopen/JS_Misc/master/docsReady.js

"use strict";

function domReady( contextWindow ) {
	if ( undefined === contextWindow ) {
		contextWindow = window;
	}

	if ( "loading" == contextWindow.document.readyState ) {
		return new Promise( function ( resolve ) {
			contextWindow.document.addEventListener( "DOMContentLoaded", function () {
				resolve( contextWindow );
			} );
		} );
	} else if ( "interactive" == contextWindow.document.readyState ) {
		return Promise.resolve( contextWindow );
	} else if ( "complete" == contextWindow.document.readyState ) {
		return Promise.reject( "document is already loaded" );
	} else {
		return Promise.reject( "unknow document ready state" );
	}
}

function allReady( contextWindow ) {
	if ( undefined === contextWindow ) {
		contextWindow = window;
	}

	if ( "complete" == contextWindow.document.readyState ) {
		return Promise.resolve( contextWindow );
	} else {
		return new Promise( function ( resolve ) {
			contextWindow.addEventListener( "load", function () {
				resolve( contextWindow );
			} );
		} );
	}
}

function frameReady( contextFrame ) {
	if ( "complete" == contextFrame.contentDocument.readyState ) {
		return Promise.resolve( contextFrame );
	} else {
		return new Promise( function ( resolve ) {
			contextFrame.addEventListener( "load", function () {
				resolve( contextFrame );
			} );
		} );
	}
}