How to use createOnloadCallbackFn method in wpt

Best JavaScript code snippet using wpt

resource-timing.js

Source:resource-timing.js Github

copy

Full Screen

...23 // Insert an empty IFrame.24 var frame = document.createElement("iframe");25 // Wait for the IFrame to load and ensure there is no resource entry for it on the timeline.26 //27 // We use the 'createOnloadCallbackFn()' helper which is normally invoked by 'initiateFetch()'28 // to avoid setting the IFrame's src. It registers a test step for us, finds our entry on the29 // resource timeline, and wraps our callback function to automatically vet invariants.30 frame.onload = createOnloadCallbackFn(test, frame, "about:blank",31 function (initiator, entry) {32 assert_equals(entry, undefined, "Inserting an IFrame with a src of 'about:blank' must not add an entry to the timeline.");33 assertInvariants(34 test,35 function () {36 test.done();37 });38 });39 document.body.appendChild(frame);40 // Paranoid check that the new IFrame has loaded about:blank.41 assert_equals(42 frame.contentWindow.location.href,43 "about:blank",44 "'Src' of new <iframe> must be 'about:blank'.");45 }46 },47 {48 description: "Setting 'document.domain' does not effect same-origin checks",49 test:50 function (test) {51 initiateFetch(52 test,53 "iframe",54 canonicalize("iframe-setdomain.sub.html"),55 function (initiator, entry) {56 // Ensure that the script inside the IFrame has successfully changed the IFrame's domain.57 assert_throws(58 null,59 function () {60 assert_not_equals(frame.contentWindow.document, null);61 },62 "Test Error: IFrame is not recognized as cross-domain.");63 // To verify that setting 'document.domain' did not change the results of the timing allow check,64 // verify that the following non-zero properties return their value.65 ["domainLookupStart", "domainLookupEnd", "connectStart", "connectEnd"]66 .forEach(function(property) {67 assert_greater_than(entry.connectEnd, 0,68 "Property should be non-zero because timing allow check ignores 'document.domain'.");69 });70 test.done();71 });72 }73 }74 ];75 // Create cached/uncached tests from the following array of templates. For each template entry,76 // we add two identical test cases to 'testCases'. The first case initiates a fetch to populate the77 // cache. The second request initiates a fetch with the same URL to cover the case where we hit78 // the cache (if the caching policy permits caching).79 [80 { initiator: "iframe", response: "(done)", mime: mimeHtml },81 { initiator: "xmlhttprequest", response: "(done)", mime: mimeText },82 // Multiple browsers seem to cheat a bit and race onLoad of images. Microsoft https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/237918783 // { initiator: "img", response: greenPng, mime: mimePng },84 { initiator: "script", response: '"";', mime: mimeScript },85 { initiator: "link", response: ".unused{}", mime: mimeCss },86 ]87 .forEach(function (template) {88 testCases.push({89 description: "'" + template.initiator + " (Populate cache): The initial request populates the cache (if appropriate).",90 test: function (test) {91 initiateFetch(92 test,93 template.initiator,94 getSyntheticUrl(95 "mime:" + encodeURIComponent(template.mime)96 + "&send:" + encodeURIComponent(template.response),97 /* allowCaching = */ true),98 function (initiator, entry) {99 test.done();100 });101 }102 });103 testCases.push({104 description: "'" + template.initiator + " (Potentially Cached): Immediately fetch the same URL, exercising the cache hit path (if any).",105 test: function (test) {106 initiateFetch(107 test,108 template.initiator,109 getSyntheticUrl(110 "mime:" + encodeURIComponent(template.mime)111 + "&send:" + encodeURIComponent(template.response),112 /* allowCaching = */ true),113 function (initiator, entry) {114 test.done();115 });116 }117 });118 });119 // Create responseStart/responseEnd tests from the following array of templates. In this test, the server delays before120 // responding with responsePart1, then delays again before completing with responsePart2. The test looks for the expected121 // pauses before responseStart and responseEnd.122 [123 { initiator: "iframe", responsePart1: serverStepDelay + "ms;", responsePart2: (serverStepDelay * 2) + "ms;(done)", mime: mimeHtml },124 { initiator: "xmlhttprequest", responsePart1: serverStepDelay + "ms;", responsePart2: (serverStepDelay * 2) + "ms;(done)", mime: mimeText },125 // Multiple browsers seem to cheat a bit and race img.onLoad and setting responseEnd. Microsoft https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/2379187126 // { initiator: "img", responsePart1: greenPng.substring(0, greenPng.length / 2), responsePart2: "0x" + greenPng.substring(greenPng.length / 2, greenPng.length), mime: mimePng },127 { initiator: "script", responsePart1: '"', responsePart2: '";', mime: mimeScript },128 { initiator: "link", responsePart1: ".unused{", responsePart2: "}", mime: mimeCss },129 ]130 .forEach(function (template) {131 testCases.push({132 description: "'" + template.initiator + ": " + serverStepDelay + "ms delay before 'responseStart', another " + serverStepDelay + "ms delay before 'responseEnd'.",133 test: function (test) {134 initiateFetch(135 test,136 template.initiator,137 getSyntheticUrl(serverStepDelay + "ms" // Wait, then echo back responsePart1138 + "&mime:" + encodeURIComponent(template.mime)139 + "&send:" + encodeURIComponent(template.responsePart1)140 + "&" + serverStepDelay + "ms" // Wait, then echo back responsePart2141 + "&send:" + encodeURIComponent(template.responsePart2)),142 function (initiator, entry) {143 // Per https://w3c.github.io/resource-timing/#performanceresourcetiming:144 // If no redirects (or equivalent) occur, this redirectStart/End must return zero.145 assert_equals(entry.redirectStart, 0, "When no redirect occurs, redirectStart must be 0.");146 assert_equals(entry.redirectEnd, 0, "When no redirect occurs, redirectEnd must be 0.");147 // Server creates a gap between 'requestStart' and 'responseStart'.148 assert_greater_than_equal(149 entry.responseStart,150 entry.requestStart + serverStepDelay,151 "'responseStart' must be " + serverStepDelay + "ms later than 'requestStart'.");152 // Server creates a gap between 'responseStart' and 'responseEnd'.153 assert_greater_than_equal(154 entry.responseEnd,155 entry.responseStart + serverStepDelay,156 "'responseEnd' must be " + serverStepDelay + "ms later than 'responseStart'.");157 test.done();158 });159 }160 });161 });162 // Create redirectEnd/responseStart tests from the following array of templates. In this test, the server delays before163 // redirecting to a new synthetic response, then delays again before responding with 'response'. The test looks for the164 // expected pauses before redirectEnd and responseStart.165 [166 { initiator: "iframe", response: serverStepDelay + "ms;redirect;" + (serverStepDelay * 2) + "ms;(done)", mime: mimeHtml },167 { initiator: "xmlhttprequest", response: serverStepDelay + "ms;redirect;" + (serverStepDelay * 2) + "ms;(done)", mime: mimeText },168 // Multiple browsers seem to cheat a bit and race img.onLoad and setting responseEnd. Microsoft https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/2379187169 // { initiator: "img", response: greenPng, mime: mimePng },170 { initiator: "script", response: '"";', mime: mimeScript },171 { initiator: "link", response: ".unused{}", mime: mimeCss },172 ]173 .forEach(function (template) {174 testCases.push({175 description: "'" + template.initiator + " (Redirected): " + serverStepDelay + "ms delay before 'redirectEnd', another " + serverStepDelay + "ms delay before 'responseStart'.",176 test: function (test) {177 initiateFetch(178 test,179 template.initiator,180 getSyntheticUrl(serverStepDelay + "ms" // Wait, then redirect to a second page that waits181 + "&redirect:" // before echoing back the response.182 + encodeURIComponent(183 getSyntheticUrl(serverStepDelay + "ms"184 + "&mime:" + encodeURIComponent(template.mime)185 + "&send:" + encodeURIComponent(template.response)))),186 function (initiator, entry) {187 // Per https://w3c.github.io/resource-timing/#performanceresourcetiming:188 // "[If redirected, startTime] MUST return the same value as redirectStart.189 assert_equals(entry.startTime, entry.redirectStart, "startTime must be equal to redirectStart.");190 // Server creates a gap between 'redirectStart' and 'redirectEnd'.191 assert_greater_than_equal(192 entry.redirectEnd,193 entry.redirectStart + serverStepDelay,194 "'redirectEnd' must be " + serverStepDelay + "ms later than 'redirectStart'.");195 // Server creates a gap between 'requestStart' and 'responseStart'.196 assert_greater_than_equal(197 entry.responseStart,198 entry.requestStart + serverStepDelay,199 "'responseStart' must be " + serverStepDelay + "ms later than 'requestStart'.");200 test.done();201 });202 }203 });204 });205 // Function to run the next case in the queue.206 var currentTestIndex = -1;207 function runNextCase() {208 var testCase = testCases[++currentTestIndex];209 if (testCase !== undefined) {210 async_test(testCase.test, testCase.description);211 }212 }213 // When a test completes, run the next case in the queue.214 add_result_callback(runNextCase);215 // Start the first test.216 runNextCase();217 /** Iterates through all resource entries on the timeline, vetting all invariants. */218 function assertInvariants(test, done) {219 // Multiple browsers seem to cheat a bit and race img.onLoad and setting responseEnd. Microsoft https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/2379187220 // Yield for 100ms to workaround a suspected race where window.onload fires before221 // script visible side-effects from the wininet/urlmon thread have finished.222 window.setTimeout(223 test.step_func(224 function () {225 performance226 .getEntriesByType("resource")227 .forEach(228 function (entry, index, entries) {229 assertResourceEntryInvariants(entry);230 });231 done();232 }),233 100);234 }235 /** Assets the invariants for a resource timeline entry. */236 function assertResourceEntryInvariants(actual) {237 // Example from http://w3c.github.io/resource-timing/#resources-included:238 // "If an HTML IFRAME element is added via markup without specifying a src attribute,239 // the user agent may load the about:blank document for the IFRAME. If at a later time240 // the src attribute is changed dynamically via script, the user agent may fetch the new241 // URL resource for the IFRAME. In this case, only the fetch of the new URL would be242 // included as a PerformanceResourceTiming object in the Performance Timeline."243 assert_not_equals(244 actual.name,245 "about:blank",246 "Fetch for 'about:blank' must not appear in timeline.");247 assert_not_equals(actual.startTime, 0, "startTime");248 // Per https://w3c.github.io/resource-timing/#performanceresourcetiming:249 // "[If redirected, startTime] MUST return the same value as redirectStart. Otherwise,250 // [startTime] MUST return the same value as fetchStart."251 assert_in_array(actual.startTime, [actual.redirectStart, actual.fetchStart],252 "startTime must be equal to redirectStart or fetchStart.");253 // redirectStart <= redirectEnd <= fetchStart <= domainLookupStart <= domainLookupEnd <= connectStart254 assert_less_than_equal(actual.redirectStart, actual.redirectEnd, "redirectStart <= redirectEnd");255 assert_less_than_equal(actual.redirectEnd, actual.fetchStart, "redirectEnd <= fetchStart");256 assert_less_than_equal(actual.fetchStart, actual.domainLookupStart, "fetchStart <= domainLookupStart");257 assert_less_than_equal(actual.domainLookupStart, actual.domainLookupEnd, "domainLookupStart <= domainLookupEnd");258 assert_less_than_equal(actual.domainLookupEnd, actual.connectStart, "domainLookupEnd <= connectStart");259 // Per https://w3c.github.io/resource-timing/#performanceresourcetiming:260 // "This attribute is optional. User agents that don't have this attribute available MUST set it261 // as undefined. [...] If the secureConnectionStart attribute is available but HTTPS is not used,262 // this attribute MUST return zero."263 assert_true(actual.secureConnectionStart == undefined ||264 actual.secureConnectionStart == 0 ||265 actual.secureConnectionStart >= actual.connectEnd, "secureConnectionStart time");266 // connectStart <= connectEnd <= requestStart <= responseStart <= responseEnd267 assert_less_than_equal(actual.connectStart, actual.connectEnd, "connectStart <= connectEnd");268 assert_less_than_equal(actual.connectEnd, actual.requestStart, "connectEnd <= requestStart");269 assert_less_than_equal(actual.requestStart, actual.responseStart, "requestStart <= responseStart");270 assert_less_than_equal(actual.responseStart, actual.responseEnd, "responseStart <= responseEnd");271 }272 /** Helper function to resolve a relative URL */273 function canonicalize(url) {274 var div = document.createElement('div');275 div.innerHTML = "<a></a>";276 div.firstChild.href = url;277 div.innerHTML = div.innerHTML;278 return div.firstChild.href;279 }280 /** Generates a unique string, used by getSyntheticUrl() to avoid hitting the cache. */281 function createUniqueQueryArgument() {282 var result =283 "ignored_"284 + Date.now()285 + "-"286 + ((Math.random() * 0xFFFFFFFF) >>> 0)287 + "-"288 + syntheticRequestCount;289 return result;290 }291 /** Count of the calls to getSyntheticUrl(). Used by createUniqueQueryArgument() to generate unique strings. */292 var syntheticRequestCount = 0;293 /** Return a URL to a server that will synthesize an HTTP response using the given294 commands. (See SyntheticResponse.aspx). */295 function getSyntheticUrl(commands, allowCache) {296 syntheticRequestCount++;297 var url =298 canonicalize("./SyntheticResponse.py") // ASP.NET page that will synthesize the response.299 + "?" + commands; // Commands that will be used.300 if (allowCache !== true) { // If caching is disallowed, append a unique argument301 url += "&" + createUniqueQueryArgument(); // to the URL's query string.302 }303 return url;304 }305 /** Given an 'initiatorType' (e.g., "img") , it triggers the appropriate type of fetch for the specified306 url and invokes 'onloadCallback' when the fetch completes. If the fetch caused an entry to be created307 on the resource timeline, the entry is passed to the callback. */308 function initiateFetch(test, initiatorType, url, onloadCallback) {309 assertInvariants(310 test,311 function () {312 log("--- Begin: " + url);313 switch (initiatorType) {314 case "script":315 case "img":316 case "iframe": {317 var element = document.createElement(initiatorType);318 document.body.appendChild(element);319 element.onload = createOnloadCallbackFn(test, element, url, onloadCallback);320 element.src = url;321 break;322 }323 case "link": {324 var element = document.createElement(initiatorType);325 element.rel = "stylesheet";326 document.body.appendChild(element);327 element.onload = createOnloadCallbackFn(test, element, url, onloadCallback);328 element.href = url;329 break;330 }331 case "xmlhttprequest": {332 var xhr = new XMLHttpRequest();333 xhr.open('GET', url, true);334 xhr.onreadystatechange = createOnloadCallbackFn(test, xhr, url, onloadCallback);335 xhr.send();336 break;337 }338 default:339 assert_unreached("Unsupported initiatorType '" + initiatorType + "'.");340 break;341 }});342 }343 /** Used by 'initiateFetch' to register a test step for the asynchronous callback, vet invariants,344 find the matching resource timeline entry (if any), and pass it to the given 'onloadCallback'345 when invoked. */346 function createOnloadCallbackFn(test, initiator, url, onloadCallback) {347 // Remember the number of entries on the timeline prior to initiating the fetch:348 var beforeEntryCount = performance.getEntries().length;349 return test.step_func(350 function() {351 // If the fetch was initiated by XHR, we're subscribed to the 'onreadystatechange' event.352 // Ignore intermediate callbacks and wait for the XHR to complete.353 if (Object.getPrototypeOf(initiator) === XMLHttpRequest.prototype) {354 if (initiator.readyState != 4) {355 return;356 }357 }358 var entries = performance.getEntries();359 var candidateEntry = entries[entries.length - 1];360 switch (entries.length - beforeEntryCount)...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1wpt.createOnloadCallbackFn();2wpt.createOnloadCallbackFn();3wpt.createOnloadCallbackFn();4 wpt.createOnloadCallbackFn = function() {5 var _this = this;6 window.onload = function() {7 _this.run();8 };9 };10 wpt.createOnloadCallbackFn = function() {11 var _this = this;12 window.onload = function() {13 _this.run();14 };15 };

Full Screen

Using AI Code Generation

copy

Full Screen

1wpt.createOnloadCallbackFn(function() {2 console.log("Onload event fired");3});4wpt.createOnloadCallbackFn(function() {5 console.log("Onload event fired");6## createOnloadCallbackFn(callback, url)7wpt.createOnloadCallbackFn(function() {8 console.log("Onload event fired");9});10wpt.createOnloadCallbackFn(function() {11 console.log("Onload event fired");12## createOnloadCallbackFn(callback, url)13wpt.createOnloadCallbackFn(function() {14 console.log("Onload event fired");15});16wpt.createOnloadCallbackFn(function() {

Full Screen

Using AI Code Generation

copy

Full Screen

1var wptCommonApi = require('./wptCommonApi.js');2var wptCommonApi = new wptCommonApi();3var callbackFn = wptCommonApi.createOnloadCallbackFn('test');4var script = document.createElement('script');5script.type = 'text/javascript';6script.onload = callbackFn;7document.head.appendChild(script);8function wptCommonApi(){9 this.createOnloadCallbackFn = function(name){10 return function(){11 console.log(name);12 }13 }14}15module.exports = wptCommonApi;16var wptCommonApi = require('./wptCommonApi.js');17var wptCommonApi = new wptCommonApi();18var callbackFn = wptCommonApi.createOnloadCallbackFn('test');19var script = document.createElement('script');20script.type = 'text/javascript';21script.onload = callbackFn;22document.head.appendChild(script);23function wptCommonApi(){24 this.createOnloadCallbackFn = function(name){25 return function(){26 console.log(name);27 }28 }29}30module.exports = wptCommonApi;31var wptCommonApi = require('./w

Full Screen

Using AI Code Generation

copy

Full Screen

1var wptdriver = require('wptdriver');2var driver = new wptdriver.Driver();3driver.createOnloadCallbackFn(function () {4 driver.log("Page loaded");5});6var wptdriver = require('wptdriver');7var driver = new wptdriver.Driver();8driver.createOnloadCallbackFn(function () {9 driver.log("Page loaded");10});11var wptdriver = require('wptdriver');12var driver = new wptdriver.Driver();13driver.runTest(function () {14 driver.log("Page loaded");15});16var wptdriver = require('wptdriver');17var driver = new wptdriver.Driver();18driver.runTest(function (done) {19 setTimeout(function () {20 driver.log("Page loaded");21 done();22 }, 1000);23});24var wptdriver = require('wptdriver');25var driver = new wptdriver.Driver();26driver.runTest(function () {27 driver.log("Page

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run wpt automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful